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

相关内容