I. Overview
The read command receives input from a standard input (keyboard), or other file descriptor. After the input is received, the Read command puts the data into a standard variable.
Ii. examples of use (here are just a few common options)
1. Basic Reading
Echo-n "Enter Your Name:"
Read name
echo "Hello $name, Welcome to my program"
Exit 0 #退出shell程序.
It is equivalent to the following:
- P "Enter Your Name:" Name #-p parameter, allows a prompt to be specified directly on the Read command line
In the above read after the variable only name one, can also have more than one, if you enter more than one data, then the first data to the first variable, the second data to the second variable. If the number of input data is too large, then all the last remaining values are given to the last variable, if too little input does not end.
2. You can also do not specify a variable on the Read command line
If you do not specify a variable, the read command places the received data in the environment variable reply
Echo $REPLY
3. Timing input
There is a potential risk of using the Read command. The script is likely to stop waiting for the user's input. If the input data script must continue, you can use the- t option to specify a timer that specifies the number of seconds the read command waits for input. When the time is full, the Read command returns a value other than 0 (0 is the normal exit state);
3. Set the character of the count input
Automatically exits when the number of characters entered reaches a predetermined number, and assigns the input data to the variable.
Esac
This example uses the-n option followed by a value of 1, which instructs the read command to exit as soon as it accepts a character. The read command immediately accepts the input and passes it to the variable as soon as it is answered by a single character. No need to press ENTER.
4. Silent Reading (input does not appear on the monitor)
Sometimes you do not want the input data to appear on the monitor. A typical example is entering a password, and of course there are many other data that need to be hidden. The- s option enables the data entered in the Read command to not appear on the monitor (in fact, the data is displayed, except that the read command sets the text color to the same color as the background).
Read- S
5. Read the file
Each call to the Read command reads "one line" of text in the file. When a file does not have a readable row, the read command exits with a non-0 status. The key to reading a file is how to transfer the data in the text to the Read command. The most common approach is to use the Cat command for a file and pass the results directly to the while command that contains the read command through the pipeline.
Count=1
Cat dat| While Read line
count=$ (($count + 1))
Done
Exit 0
Shell's Read command