Example-1: Using simple read command
In this example, a single data is taken from the user and we print the value. After running the script, the program will wait for the user input. When the user types the data and presses enter then the data will be stored in answer variable. The value of answer variable is printed later. One thing, you should remember that you don’t need to use ‘$’ symbol at the time of assigning a variable’s value but you have to use ‘$’ symbol at the time of reading the variable.
echo -n "What is your favorite food : "
echo "Oh! you like $answer!"
Example-2: Using read command with options
-p option is used with read command to display some helpful message for the user related to input. -s option is used to hide the text from the terminal which will be typed by the user. This is called silent mode and used for password data. The following example shows the use of both options.
# Type your Login Information
read -p ‘Username: ‘ user
read -sp ‘Password: ‘ pass
if (( $user == "admin" && $pass == "12345" ))
echo -e "nSuccessful login"
echo -e "nUnsuccessful login"
Example-3: Using read command to take multiple inputs
If you want to take multiple inputs at a time then you have to use read command with multiple variable names. In the following example, four inputs are taken in four variables by using read command.
# Taking multiple inputs
echo "Type four names of your favorite programming languages"
read lan1 lan2 lan3 lan4
echo "$lan1 is your first choice"
echo "$lan2 is your second choice"
echo "$lan3 is your third choice"
echo "$lan4 is your fourth choice"
Example-4: Using read command with the time limit
If you want to set time restricted input for the user then you have to use -t option with a read command. Here, time is counted as second. In the following example, the program will wait for 5 seconds for user’s input and if the user is unable to type the data within 5 seconds then the program will exit without value.
read -t 5 -p "Type your favorite color : " color
So, you can retrieve input from the user in different ways using read command based on the requirement of your script.
For more information watch the video!