-
Book Overview & Buying
-
Table Of Contents
Linux Shell Scripting Cookbook, Second Edition - Second Edition
read is an important Bash command to read text from the keyboard or standard input. We can use read to interactively read an input from the user, but read is capable of much more. Most of the input libraries in any programming language read the input from the keyboard; but string input termination is done when return is pressed. There are certain critical situations when return cannot be pressed, but the termination is done based on a number of characters or a single character. For example, in a game, a ball is moved upward when + is pressed. Pressing + and then pressing return every time to acknowledge the + press is not efficient. In this recipe we will use the read command that provides a way to accomplish this task without having to press return.
You can use various options of the read command to obtain different results as shown in the following steps:
The following statement will read n characters from input into the variable_name variable:
read -n number_of_chars variable_name
For example:
$ read -n 2 var $ echo $var
Read a password in the nonechoed mode as follows:
read -s var
Display a message with read using:
read -p "Enter input:" var
Read the input after a timeout as follows:
read -t timeout var
For example:
$ read -t 2 var #Read the string that is typed within 2 seconds into variable var.
Use a delimiter character to end the input line as follows:
read -d delim_char var
For example:
$ read -d ":" var hello:#var is set to hello
Change the font size
Change margin width
Change background colour