The read
command is a powerful tool in Bash scripting that allows you to capture user input and store it in variables. When it comes to assigning Bash line input to multiple variables, the read
command is the primary method you'll use.
Basic Usage of the read
Command
The basic syntax for the read
command is as follows:
read var1 [var2 var3 ...]
Here, var1
, var2
, var3
, and so on are the variables that will store the user input. If you provide more variable names than the number of words in the input, the extra variables will be assigned empty values.
read name age gender
echo "Name: $name"
echo "Age: $age"
echo "Gender: $gender"
In this example, the read
command captures the user input and assigns the first word to name
, the second word to age
, and the third word to gender
.
Handling Newlines and Whitespace
By default, the read
command splits the input on whitespace (spaces, tabs, or newlines). If you need to capture input that contains newlines or other whitespace characters, you can use the -r
(raw) option.
read -r multiline_input
echo "$multiline_input"
In this example, the -r
option ensures that the read
command preserves the newline characters in the user input, which is then stored in the multiline_input
variable.
To provide a prompt for the user input, you can use the -p
option with the read
command.
read -p "Enter your name: " name
echo "Hello, $name!"
In this example, the -p
option displays the "Enter your name: " prompt before capturing the user's input and storing it in the name
variable.
By understanding the various options and behaviors of the read
command, you can effectively capture and distribute Bash line input across multiple variables, tailoring the input capture process to your specific needs.