In the last chapter, you learned about shell and environment variables. You also learned about how to export environment variables, read-only variables, command-line arguments, and create/handle arrays.
In this chapter, we will cover following topics:
here operator (<<) and here string (<<<)The read command is a shell built-in command for reading data from a file or keyboard.
The read command receives the input from the keyboard or a file until it receives a newline character. Then, it converts the newline character into a null character:
read variable echo $variable
This will receive text from the keyboard. The received text will be stored in the variable.
–p option. The option -p displays the text that is placed after –p on the screen:#!/bin/bash # following line will print "Enter value: " and then read data # The received text will be stored in variable value read -p "Enter value : " value
Output:
Enter value : abcd
read command, then the received data or text will be stored in a special built-in variable called REPLY. Let's write a simple script read_01.sh, shown as follows:#!/bin/bash echo "Where do you stay ?" read # we have not supplied any option or variable echo "You stay in $REPLY"
Save the file, give the permission to execute, and run the script as follows:
$ chmod u+x read_01.sh $ ./read_01.sh
Output:
"Where do you stay?" Mumbai "You stay at Mumbai"
read_02.sh. This script prompts the user to enter their first and last name to greet the user with their full name:#!/bin/bash echo "Enter first Name" read FIRSTNAME echo "Enter Last Name" read LASTNAME NAME="$FIRSTNAME $LASTNAME" echo "Name is $NAME"
$ read value1 value2 value3
Let's write Shell script read_03.sh, shown as follows:
#!/bin/bash echo "What is your name?" read fname mname lname echo "Your first name is : $fname" echo "Your middle name is : $mname" echo "Your last name is : $lname"
Save the file, give the permission to execute, and run the script as follows:
What is your name? Ganesh Sanjiv Naik "Your first name is : Ganesh" "Your middle name is : Sanjiv" "Your last name is : Naik"
#!/bin/bash
echo -n "Name few cities? "
read -a cities
echo "Name of city is ${cities[2]}."Save the file, give the permission to execute, and run the script as follows:
Name few cities? Delhi London Washington Tokyo Name of city is Washington.
In this case, the list of cities is stored in the array of cities. The elements in the array are here:
cities[0] = Delhi cities[1] = London cities[2] = Washington cities[3] = Tokyo
The index of the array starts with 0, and in this case, it ends at 3. In this case, four elements are added in the cities[] array.
read command along with one unused variable, shown as follows:Echo "Please press enter to proceed further " read temp echo "Now backup operation will be started ! "
The following table summarizes various read command-related options that you learned in the previous sections: