To read an input from the user, use the “read” command.
The read command will take the input from the user and assigns to a variable.
Syntax: read <variable_name> example: read website_name
read -p option:
If you want to display a help text to the user, then use “-p” option.
Example 1:
read -p “Enter user name” <variable_name>
read -s option:
When the user enters a value, that value will be displayed in the terminal. To do a silent read, we use “-s” option. This is generally used when we are reading a password value.
Example 2:
I have created a shell script with below program.
#!/bin/bash
read -p “Enter user name  = ” user_name
read -s -p “Enter password = ” password
echo -e “\n\n\nYou have entered ” #use -e to accept escape sequence
echo “user name = $user_name”
echo “Password is = $password”
Output:

As shown above, while entering user name, the input is displayed. But while entering the password, the value is not displayed, because we have used “-s” option.

Example 3:
If you want to store multiple variables inside an array, use “-a” option in read function. “-a” option will instruct shell to read an array. Then while printing the value, display one by one by using the index value.

#!/bin/bash
echo “Enter multiple items”
read -a items

echo “Items : ${items[0]} ${items[1]} ${items[2]} ${items[3]} ”

Output:
Enter multiple items
pro developer tutorial
Names : pro developer tutorial

Example 4:
If you don’t give any variable name while using read command, then if any input provided by the user will go to a special variable called as “REPLY”.

#!/bin/bash
echo “Enter website name”
read
echo “The website name is $REPLY”

Output:
Enter website name
prodevelopertutorial.com
The website name is prodevelopertutorial.com

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *