如果没有来自用户的回复,则执行命令

时间:2014-01-13 07:34:47

标签: shell command-line

我正在编写一个脚本,必须等待一段时间。如果用户在该时间内未收到回复,则必须退出脚本。

例如

printf " **YES or NO** "
read choice

if [[ $choice == "yes" ]] ; then
    some commends
else
    exit 0
fi

如果用户在30秒内未回复[是或否],则必须转到“其他”分支。

我们怎么做?

我试过这样:

read choice || sleep 30

1 个答案:

答案 0 :(得分:0)

read-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