Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

Linux Shell 腳本實現人機互動倒數確認

有些批次任務執行前需要先讓使用者確認,若無人回應則在數秒後自動繼續。利用 stty 調整終端機的輸入模式,就能做出帶倒數的互動提示。

腳本內容

while true; do
    stty -icanon min 0 time 100
    echo -n "Automatic execute ten seconds after, Are you sure you want to start the task (yes or no)?"
    read Arg
    case $Arg in
        Y|y|YES|yes)
            break;;
        N|n|NO|no)
            exit;;
        "")
            # 未輸入任何內容,自動繼續
            break;;
    esac
done

echo
echo "others function..."

關鍵說明

stty -icanon 關掉正規模式,讓 read 不必等使用者按下 Enter;min 0 表示最少 0 個字元就返回;time 100 是等待 10 秒(單位為 0.1 秒),逾時後 read 會拿到空字串。

case 分支的設計是:輸入 y 系列就 break 往下執行,輸入 n 系列直接 exit 結束,空白則視為默許並自動繼續。這樣即使無人值守,排程任務也不會被卡住。

Copyright © Linux教程網 All Rights Reserved