
The read command can be used to prompt a user for input. For example, let's say you have a bash shell script that has the following.
#!/bin/bash
read name
echo "Your name is" $name
When running the bash shell script, there will be a flashing cursor where you can enter input. In this example, John Doe is entered, and Your name is John Doe is returned.
~]# bash example.sh
John Doe
Your name is John Doe
Add text to the prompt
The prior example is not very practical, because there is just a flashing cursor with no message that describes the expected input. The -p option can be used to add a message to the prompt.
#!/bin/bash
read -p "Enter your name: " name
echo "Your name is" $name
Now, when running the script, there will be a message so that you know what to type.
[root@server1 ~]# bash example.sh
Enter your name:
Allow \ character
By default, the read command will escape the \ character. In this example, the \ character is escaped and not included in the output.
[root@server1 ~]# bash example.sh
Enter your name: Jo\hn D\oe
Your name is John Doe
The -r option can be used to allow the \ character.
#!/bin/bash
read -r -p "Enter your name :" name
echo "Your name is" $name
Now, the \ character will be displayed in the output.
[root@server1 ~]# bash example.sh
Enter your name: Jo\hn D\oe
Your name is Jo\hn D\oe
New line
The -rep option and $ character can be used to create new lines in the read command.
#!/bin/bash
read -rep $'How many MB should the new JVM be (128 256 512 1024)?\n>' SIZE
This is useful so that the cursor that prompts the users for input appears below the text of the read command.
[root@server1 ~]# bash example.sh
How many MB should the new JVM be (128 256 512 1024)?
>
Timeout due to inactivity
The -t option can be used to cause the read command to timeout if input is not submitted within a certain time period. In this example, if there is no input in 60 seconds, the read command will timeout.
#!/bin/bash
read -t 60 -p "Enter your name :" name
echo "Your name is" $name
In this example, no input is submitted within 60 seconds, and the name variable is empty.
[root@server1 ~]# bash example.sh
Enter your name:
Your name is
If / else
The read command is very helpful when used in combination with an if else statement. In this example, the read command is used to ask a user if they really want to delete a file. If the user types Y, test_file is deleted. If the user types N, test_file is not deleted.
#!/bin/bash
read -p "Are you sure you want to delete this file? Y for yes, N for no : " answer
if [ $answer == "Y" ]
then
rm test_file
echo "The file has been deleted"
else
echo "The file has not been deleted"
fi
Did you find this article helpful?
If so, consider buying me a coffee over at