2014-01-13 14 views
0

我正在寫一個腳本,必須等待一段時間。如果用戶在那段時間內沒有得到回覆,腳本必須退出。如果沒有用戶回覆,執行命令

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

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

如果用戶沒有回覆[yes或no]將30秒鐘,這兩點必須去爲「其他」分枝內。

我們該怎麼做?

我想是這樣的:

read choice || sleep 30 
+0

讀取輸入<的/ dev/tty的取決於你在哪裏 –

回答

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 
+0

感謝伊戈爾.. 它爲我讀書。 – prabhu

+0

然後請考慮[將此答案標記爲已接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – tripleee

+0

@Igor Chubin,您的腳本在最後一部分中無法正常工作。在閱讀後,如果答案不是「是」,那麼最後的其他部分將執行,但執行第二個部分,所以我在帖子中做了一些更改。 – Kalanidhi