Shell Script – Read User Input

In this article, let us see how to get input from user in a Shell script using read command.

Command Usage :

read <options> variable_name_1 variable_name_2 variable_name_N<variable>

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 is just to inform user to input name
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 :

$ sh sc_5_read_input.sh
Enter Name
Sibi
Name is Sibi

Read using Delimiter option :

$ read -d "#" var_name
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 :

$ read -n 2 var_num
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.

Technology: 

Search