BASH Programming System Administration

Bash Script User Input

Taking input from the user is a common task for any programming language. You can take input from a user in bash script in multiple ways. A read command is used in the bash script to take data from the user.  Single or multiple data can be taken in bash script by applying different options of the read command. Some common uses of the read command are shown in this tutorial.

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 : "
read answer
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
echo $color


So, you can retrieve input from the user in different ways using read command based on the requirement of your script.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.