The linux read command is used to take a user input from the command line. This is useful when we want to provide user interactivity at runtime.
The read syntax is:
read [options] variable_name
We can then use the
$ sign in front of the variable name to access its value, e.g.
Bash Script to Read User Input
Start by creating a file with
.sh extension, e.g.:
Then open then file in your favorite editor and type the following:
#!/bin/bash echo "Enter your name:" read name echo "Enter your age:" read age echo "Hello" $name, "you are" $age "years old"
The above script takes a user’s name and age.
To run the above script, open a terminal and type:
$ sh user_input.sh Enter your name: DevQA Enter your age: 12 Hello DevQA, you are 12 years old
Prompt Message With read Command
To prompt a message with the read command, we use the
$ read -p "Enter your username: " username
If we don’t want the characters to be displayed on the screen, we need to use the
-s option with the read command. This is useful for when we are reading passwords.
$ read -sp "Enter your password: " password
Your bash script to read the above user inputs would look like:
#!/bin/bash read -p "Enter your username: " username read -sp "Enter your password: " password echo -e "\nYour username is $username and Password is $password"
The output is:
$ sh user_input.sh Enter your username: devqa Enter your password: Your username is devqa and Password is secret