簡體   English   中英

確認Shell腳本輸入

[英]Confirming Shell Script Input

我正在編寫腳本以執行重復性任務,該任務僅更改基本值和位置(例如用戶名)。

我已經編寫了提示用戶名並驗證用戶名尚未使用的代碼。 我現在嘗試提示用戶,如果收到的腳本輸入正確並且不更改它。 我的問題是,如果輸入正確,它將不斷循環。 有人有什么建議嗎?

clear
confirm () {
    # call with a prompt string or use a default
    echo "CMIT # ${1}"
    read -r -p "CMIT [Y/n/q] > " answer
    case "${answer}" in
        [yY]|[yY][eE][sS]) false ;;
        [nN]|[nN][oO]) true ;;
        [qQ]|[qQ][uU][iI][tT]) exit 1 ;;
    esac
}

while true;  do
    OE_USER=
    while (id -u $OE_USER > /dev/null 2>&1); do
        echo "CMIT # What user will this run under?"
        read -r -p "CMIT > " OE_USER
        if id -u $OE_USER > /dev/null 2>&1; then
            echo "CMIT # Bad User Name. Try Again"
        fi
    done
    clear
    confirm "Continue installing using '$OE_USER' as the server name?"
done

哇。 愚蠢的問題。 抱歉。

clear
GO=true
confirm () {
    # call with a prompt string or use a default
    echo "CMIT # ${1}"
    read -r -p "CMIT [Y/n/q] > " answer
    case "${answer}" in
        [yY]|[yY][eE][sS]) GO=false ;;
        [nN]|[nN][oO]) GO=true ;;
        [qQ]|[qQ][uU][iI][tT]) exit 1 ;;
    esac
}

while $GO;  do
    OE_USER=
    while (id -u $OE_USER > /dev/null 2>&1); do
        echo "CMIT # What user will this run under?"
        read -r -p "CMIT > " OE_USER
        if id -u $OE_USER > /dev/null 2>&1; then
            echo "CMIT # Bad User Name. Try Again"
        fi
    done
    clear
    confirm "Continue installing using '$OE_USER' as the server name?"
done
GO=true

您可以聲明一個在全局確認函數中設置好的全局標志,以得到一個很好的答案,也可以在confirm內部使用return語句,該語句在while循環中的條件條件下進行測試。

還有其他選項,例如在測試用戶輸入后使用遞歸調用。 這將消除對while循環的需求,但是會產生使初始輸入也成為函數的需求。

您可以使用函數的退出狀態:

更改“是”情況以執行“ true”,更改“否”情況以執行“ false”。 然后

while true; do
    # ...
    if confirm "Continue installing using '$OE_USER' as the server name?" 
    then
        break
    fi
done

暫無
暫無

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

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