Chapter 3: Prompting for input
—
read can be used to prompt for user input:
1 read -p "Prompt: " var_name
2
3 # Use -s to silence screen input for passwords, example
4 read -sp "Enter password: " user_password
If we do not supply the variable name to the read command, the value will be stored in $REPLY
Another way to read is using heredoc notation, which we will see later in the book:
1 read var1 var2 <<< "Hello World"
2 echo $var1
3 echo $var2
If we use the -n option followed by an integer, we can specify the number of characters to accept before continuing. For example, if you want to read only 1 character, use read -n1 - there’s no need for the user to hit enter after providing the input.
We can also accept user input in an array with the read -a flag. Note that indexing is 0-based:
1 read -a array_var name age email
2 # ${array[@]} will loop through all variables
3 echo "Your name, age, email are: ${array_var[@]}"
4
5 # Iterate through indexes 0 to 1
6 echo "Your name and age are: ${array_var:0:1}"
7
8 # Access value at index 2
9 echo "Your email is ${array_var[2]}"