簡體   English   中英

Bash腳本倒計時器需要檢測任何鍵才能繼續

[英]Bash script countdown timer needs to detect any key to continue

我需要在倒數計時器循環中收聽任何按鍵。 如果按下任何鍵,則倒數計時器應該突破它的循環。 這主要是有效的,除了輸入鍵只是讓倒數計時器更快。

#!/bin/bash
for (( i=30; i>0; i--)); do
    printf "\rStarting script in $i seconds.  Hit any key to continue."
    read -s -n 1 -t 1 key
    if [[ $key ]]
    then
        break
    fi
done
echo "Resume script"

我似乎無法找到任何在線任何位置檢測輸入密鑰的示例。

我認為基於read的返回代碼, read解決這個問題。 readman頁,

The return code is zero, unless end-of-file is encountered, read times out,
or an invalid file descriptor is supplied as the argument to -u.

超時的返回碼似乎是142 [在Fedora 16中驗證]

所以,腳本可以修改為,

#!/bin/bash
for (( i=30; i>0; i--)); do
    printf "\rStarting script in $i seconds.  Hit any key to continue."
    read -s -n 1 -t 1 key
    if [ $? -eq 0 ]
    then
        break
    fi
done
echo "Resume script"

問題是默認情況下 read會將換行符視為分隔符。

設置IFS為null,以避免讀取高達分隔符。

說:

IFS= read -s -N 1 -t 1 key

相反,你會在read過程中按Enter鍵獲得預期的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM