Bash:while循環沒有輸出,還有更好的解決方案嗎?

Bash:while循環沒有輸出,還有更好的解決方案嗎?

我是 bash 腳本新手,下面的腳本部分沒有給我任何輸出。

check=""
while [ "$check"=="" ]
do
    read -p "Signature Correct?(Yes/No): " check

if [ "$check" != "Y" || "$check" != "y" || "$check" != "Yes" || "$check" != "yes" || "$check" != "N" || "$check" != "n" || "$check" != "No" || "$check" != "no" ];
then
    check=""
elif ["$check" == "Y" || "$check" == "y" || "$check" == "Yes" || "$check" == "yes" ];
then
    echo "Signature Accepted!"
elif [ "$check" != "N" || "$check" != "n" || "$check" != "No" || "$check" != "no" ];
then
    check=""
fi
done

我沒有收到任何錯誤訊息。有什麼幫助嗎?如果您有更聰明或更短的解決方案,我將很高興從這些知識中受益。

謝謝你!

答案1

建議:

#!/bin/bash

while true; do
    read -p 'Is signature correct? y/[n]: '

    [[ $REPLY == [Yy]* ]] && break

    echo 'Ok, asking again...'
done

echo 'Signature accepted'

y這實現了一個無限循環,用戶透過輸入以or開頭的字串來打破該循環,Y但預設將輸入解釋為「no」。

如果您需要檢查YyYesyes(即,將字串視為yup“no”),請使用

case $REPLY in ([Yy]|[Yy]es) break; esac

而不是[[ ... ]]測試 和break

答案2

這裡有兩種不同的方式。第一個使用正規表示式來匹配是/否,另一個使用select內建表達式:

#!/bin/bash

echo "Version 1"

check=
while [[ -z $check ]]; do
    read -r -p "Signature Correct? (Yes/No): " check
    if [[ $check =~ ^[Nn]o?$ ]]; then
        echo "Try again"
        check=
    elif [[ $check =~ ^[Yy](es)?$ ]]; then
        echo "Signature accepted"
        break;
    else
        echo "Invalid input."
        check=
    fi
done

echo "Version 2"

PS3="Signature Correct? (1 for Yes/ 2 for No): "
select opt in Yes No; do
    case $opt in
        Yes)
            echo "Signature accepted"
            break;;
        No)
            echo "Try again.";;
        *)
            echo "Invalid input."
    esac;
done

相關內容