Bash Read User Input
To read user input from bash terminal, use read command followed by the variable names.
In this tutorial, we shall learn to read input provided by user through bash shell (Terminal), using example bash scripts.
Syntax of Read Command
read is a bash builtin command to read input from user. read command reads only a single line from bash shell. Following is the syntax of read command
read <variable_name>
Example – Read Input from User via Terminal
Following is an example Bash Script to read user input using read command.
Bash Script
#!/bin/bash
echo "Enter your name.."
read name
echo "Hello $name ! Learn to Read input from user in Bash Shell"
In this example, third line, echo command is used to prompt user for an input.
Fourth line, read command reads user input via keyboard, to a variable named name
.
Fifth line, echo command uses name
variable to display to the terminal.
Output
$ ./bash-readinput-example
Enter your name..
Arjun
Hello Arjun ! Learn to Read input from user in Bash Shell
Read input to multiple variables in a single read command
You may also read input to multiple variables in a single read command.
In the following example, we shall read firstname followed by lastname in a single read command.
Bash Script
#!/bin/bash
echo "Enter your FirstName LastName.."
read firstname lastname
echo "Hello $firstname ! Heard that your last name is $lastname."
The user input is broken to parts at white-space characters and the chunks are assigned to respective variables. Following are the possible scenarios with the number of words and number of variables.
Scenario | Result |
---|---|
Number of Words = Number of Variables | Variables are assigned with words respectively |
Number of Words < Number of Variables | Respective Words are assigned to Variables. Remaining variables remain empty. |
Number of Words > Number of Variables | Respective Words are assigned to Variables. Except for the last variable is assigned the rest of input. |
Based on this, the first example where we read a line to variable could be considered as a third scenario in the table above with number of variables = 1.
Output
$ ./bash-readinput-example-2
Enter your firstname lastname..
Tutorial Kart
Hello Tutorial ! Heard that your last name is Kart.
$ ./bash-readinput-example-2
Enter your firstname lastname..
X Y
Hello X ! Heard that your last name is Y.
arjun@arjun-VPCEH26EN:~/workspace/bash/readinput$ ./bash-readinput-example-2
Enter your firstname lastname..
Monica
Hello Monica ! Heard that your last name is .
Conclusion
In this Bash Tutorial, we learned how to read user input, entered via standard input, to a variable and use the value in the script.