Bash Read User Input

Bash Read User Input

Bash Read User Input – In this Bash Tutorial, we shall learn to read input provided by user through bash shell (Terminal), using example bash scripts.

Read builtin command

Read a line – using read builtin 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

Following is an Example Bash Script to read user input using read command.

In the example above, we have read user input to a bash variable  name  and used it in the next bash echo command.

 

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.

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.

ScenarioResult
Number of Words = Number of VariablesVariables are assigned with words respectively
Number of Words < Number of VariablesRespective Words are assigned to Variables. Remaining variables remain empty.
Number of Words > Number of VariablesRespective 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.