In this article, let us see how to get input from user in a Shell script using read command.
Command Usage :
Options are,
-d delimiter -> the first delimiter character is used to stop the user input rather than new line character.
-n number_of_chars -> this ‘n’ decides the number of characters that the user can input
Consider the below sample shell script which demonstrates how to get user input.
Sample script :
echo "Enter Name"
# The below read command get the user input from input stream and stores in name variable
read name
# This is a simple check to alert user whether he entered name or not.
if [ ! -z $name ]
then
echo "Name is ${name}"
else
echo "Please enter valid name"
fi
Output :
Enter Name
Sibi
Name is Sibi
Read using Delimiter option :
I am testing delimiter option in read command
Till I press the Hash symbol I can input as much I want
Now I am going to press the hash symbol. This would exit me from giving user input.
#
Read using –n option :
98
The above –n option will allow the user to enter only 2 characters. After entering 2 characters it will automatically stops the user from entering data.
In this article, we have illustrated the basic usage of read command and its commonly used options. For more information about the read command options, refer the Unix manual pages.