Content #
使用read命令时要当心。脚本可能会一直苦等着用户输入。如果不管是否有数据输入,脚本都必须继续执行,你可以用-t选项来指定一个计时器。-t选项会指定 read命令等待输入的秒数。如果计时器超时,则read命令会返回非0退出状态码:
$ cat asknametimed.sh
#!/bin/bash
# Using the read command with a timer
#
if read -t 5 -p "Enter your name: " name
then
echo "Hello $name, welcome to my script."
else
echo
echo "Sorry, no longer waiting for name."
fi
exit
$
$ ./asknametimed.sh
Enter your name: Christine
Hello Christine, welcome to my script.
$
$ ./asknametimed.sh
Enter your name:
Sorry, no longer waiting for name.
$
我们可以据此(如果计时器超时,则read命令会返回非0退出状态码)使用标准的结构化语句(比如if-then语句或while循环)来轻松地梳理所发生的具体情况。在本例中,计时器超时,if语句不成立,shell执行的是else部分的命令。
你也可以不对输入过程计时,而是让read命令统计输入的字符数。当字符数达到预设值时,就自动退出,将已输入的数据赋给变量:
$ cat continueornot.sh
#!/bin/bash
# Using the read command for one character
#
read -n 1 -p "Do you want to continue [Y/N]? " answer
#
case $answer in
Y | y) echo
echo "Okay. Continue on...";;
N | n) echo
echo "Okay. Goodbye"
exit;;
esac
echo "This is the end of the script."
exit
$
$ ./continueornot.sh
Do you want to continue [Y/N]? Y
Okay. Continue on...
This is the end of the script.
$
$ ./continueornot.sh
Do you want to continue [Y/N]? n
Okay. Goodbye
$
本例中使用了-n选项和数值1,告诉read命令在接收到单个字符后退出。只要按下单个字符进行应答,read命令就会接受输入并将其传给变量,无须按Enter键。
From #
Linux命令行与shell脚本编程大全