We use the read command to accept the user's input from the keyboard.
Example:
Accepting a user's name
#! /bin/bash
echo "Enter your name: "
read name
echo "Hello there $name"
In the above example the read command stores the input from the keyboard into the variable name.
Accepting multiple inputs
#! /bin/bash
echo "Enter the names of your mother and father : "
read father mother
echo "Hello there Mr. $father and Mrs $mother"
$ ./inputs.sh
Enter the names of your mother and father :
Roger Rouge
Hello there Mr. Roger and Mrs Rouge
Don't press the enter key after entering the value into the first variable, instead press space and enter the value into the next variable.
In the above two examples we can observe that the prompt text (Enter your name) and the input promt are on separate lines. If we want them to come on the same line we can use the read -p command.
#! /bin/bash
read -p "Enter the names of your mother and father : " father mother
echo "Hello there Mr. $father and Mrs $mother"
$ ./hello-world.sh
Enter the names of your mother and father : Roger Rouge
Hello there Mr. Roger and Mrs Rouge
To obscure the text during input then use the -s option
#! /bin/bash
read -sp "Enter your Password: " $password
echo "Your password is: $password"
$ ./obscure-text.sh
Enter your Password:
Your password is: mypassword
If no variable is given along with the read command then it stores it in the $REPLY variable by default.
#! /bin/bash
read
echo "Your text is: $REPLY"
$ ./default-input.sh
Hello
Your text is: Hello
You can use read -a command to store the input in an array
#! /bin/bash
echo "Enter the names"
read -a names
echo "Hello there ${names[0]} and ${names[1]}"
$ ./array-input.sh
Enter the names
Dragon Luffy
Hello there Dragon and Luffy
The arguments passed to a shell script is stored in the variables $1, $2, and so on. The name of the script in stored in the $0 variable.
#! /bin/bash
echo "The arguments are : " $1 $2 $3
$ ./command-line-argument-1.sh hello there world
"The arguments are :
Argument 1 : hello
Argument 2 : there
Argument 3 : world
To accept the arguments as array we can use the $@ variable. This variable holds the arguments in the form of an array. An important thing to note here is that the name of the script will not be store in the array and hence we should start accessing the array from index 0.
The $# variable contains the number of command-line arguments passed to the script.
#! /bin/bash
args=("$@")
echo "The arguments are : "
echo "Argument 1 : ${args[0]}"
echo "Argument 2 : ${args[1]}"
echo "Argument 3 : ${args[2]}"
echo "All the arguments : $@"
echo "Number of arguments : $#"
./command-line-argument-2.sh hello there world
The arguments are :
Argument 1 : hello
Argument 2 : there
Argument 3 : world
All the arguments : hello there world
Number of arguments : 3