Content #
read命令从标准输入(键盘)或另一个文件描述符中接受输入。获取输入后, read命令会将数据存入变量。
$ cat askname.sh
#!/bin/bash
# Using the read command
#
echo -n "Enter your name: "
read name
echo "Hello $name, welcome to my script."
exit
$
$ ./askname.sh
Enter your name: Richard Blum
Hello Richard Blum, welcome to my script.
$
注意,用于生成提示的echo命令使用了-n选项。该选项不会在字符串末尾输出换行符,允许脚本用户紧跟其后输入数据。这让脚本看起来更像表单。
实际上,read命令也提供了-p选项,允许直接指定提示符:
$ cat askage.sh
#!/bin/bash
# Using the read command with the -p option
#
read -p "Please enter your age: " age
days=$[ $age * 365 ]
echo "That means you are over $days days old!"
exit
$
$ ./askage.sh
Please enter your age: 30
That means you are over 10950 days old!
$
你会注意到,当在第一个例子中输入姓名时,read命令会将姓氏和名字保存在同一个变量中。read命令会将提示符后输入的所有数据分配给单个变量。如果指定多个变量,则输入的每个数据值都会分配给变量列表中的下一个变量。如果变量数量不够,那么剩下的数据就全部分配给最后一个变量:
$ cat askfirstlastname.sh
#!/bin/bash
# Using the read command for multiple variables
#
read -p "Enter your first and last name: " first last
echo "Checking data for $last, $first..."
exit
$
$ ./askfirstlastname.sh
Enter your first and last name: Richard Blum
Checking data for Blum, Richard...
$
也可以在read命令中不指定任何变量,这样read命令便会将接收到的所有数据都放进特殊环境变量REPLY中:
$ cat asknamereply.sh
#!/bin/bash
# Using the read command with REPLY variable
#
read -p "Enter your name: "
echo
echo "Hello $REPLY, welcome to my script."
exit
$
$ ./asknamereply.sh
Enter your name: Christine Bresnahan
Hello Christine Bresnahan, welcome to my script.
$
REPLY环境变量包含输入的所有数据,其可以在shell脚本中像其他变量一样使用。
From #
Linux命令行与shell脚本编程大全