Shell 如果没有用户的回复,则执行命令
我正在写一个剧本,必须等一段时间。如果用户在这段时间内没有得到回复,脚本必须退出 乙二醇 如果用户在30秒内没有回复[是或否],则必须转到else分支 我们怎么做 我试着这样做:Shell 如果没有用户的回复,则执行命令,shell,command-line,Shell,Command Line,我正在写一个剧本,必须等一段时间。如果用户在这段时间内没有得到回复,脚本必须退出 乙二醇 如果用户在30秒内没有回复[是或否],则必须转到else分支 我们怎么做 我试着这样做: read choice || sleep 30 使用带-t超时键的读取 -t timeout Cause read to time out and return failure if a complete line of input is not
read choice || sleep 30
使用带-t超时键的读取
-t timeout
Cause read to time out and return failure if a complete
line of input is not read within timeout seconds. time‐
out may be a decimal number with a fractional portion
following the decimal point. This option is only effec‐
tive if read is reading input from a terminal, pipe, or
other special file; it has no effect when reading from
regular files. If timeout is 0, read returns success if
input is available on the specified file descriptor,
failure otherwise. The exit status is greater than 128
if the timeout is exceeded.
因此,在你的情况下:
read -t 30 answer
[ "$?" > 128 ] && TIMEOUT=YES
if [ "$answer" = yes ]
then
echo User replied yes
else
if [ "$TIMEOUT" = YES ]
then
echo User did not reply
else
echo User replied something other
fi
fi
读输入然后请考虑。@ Igor Chubin,你的脚本在最后一个部分中不能正常工作。阅读后,如果答案不是“是”,那么最后一个else部分将执行,但执行第二个else部分,因此我在文章中做了一些更改。
read -t 30 answer
[ "$?" > 128 ] && TIMEOUT=YES
if [ "$answer" = yes ]
then
echo User replied yes
else
if [ "$TIMEOUT" = YES ]
then
echo User did not reply
else
echo User replied something other
fi
fi