shell 脚本编写 - 在一个 if 语句中进行多个相等测试

shell 脚本编写 - 在一个 if 语句中进行多个相等测试

因此,我创建了一个脚本,它工作得很好,除了最后当我输入饮料时,它执行了一行不应该执行的行。最后一行只会在我输入“no”或“No”时出现......我做错了什么?

echo -n "Are you thirsty?"
read th

if [ "$th" = "yes" ] || [ "Yes" ]; then
    echo "What would you like to drink?"
    read th
fi

if [ "$th" = "water" ]; then
    echo "Clear crisp and refreshing."
elif [ "$th" = "beer" ]; then
    echo "Let me see some ID."
elif [ "$th" = "wine" ]; then
    echo "One box or Two?"
else
    echo "Coming right up."
fi

if [ "$th" = "no" ] || [ "No" ]; then
    echo "Come back when you are thirsty."
fi

答案1

你的问题是[ "Yes" ][ "No" ]相当于[ -n "Yes" ][ -n "No" ]因此总是评估为真。

正确的语法是:

if [ "$th" = "yes" ] || [ "$th" = "Yes" ]; then
...
if [ "$th" = "no" ] || [ "$th" = "No" ]; then

或者:

if [ "$th" = "yes" -o "$th" = "Yes" ]; then
...
if [ "$th" = "no" -o "$th" = "No" ]; then

或者,如果您使用bashBourne shell 解释器:

if [ "${th,,}" = "yes" ]; then
...
if [ "${th,,}" = "no" ]; then

${th,,}用变量的小写值替换th

答案2

您的测试没有按照您的想法进行。

if [ "$var" = "value" ] || [ "Value" ];

这不会进行两次相等测试。它检查第一种情况,然后,如果失败,则检查是否"Value"存在,它确实这样做了,因为它是要检查的。所以它总是传递到then与 相对应的if。您可能想要:

if [ "$var" = value" ] || [ "$var" = "Value" ]

更好的方法可能是查看一个case..esac块:

case "$var" in
    value|Value)
        do_stuff
        ;;
    other|Other)
        do_something_else
        ;;
esac

答案3

(1) 当你测试[ "Yes" ]和之后的时[ "No" ],你仍然需要将它th与两个部分进行比较:

[ "$th" = "yes" ] || [ "$th" = "Yes" ]

[ "$th" = "no" ] || [ "$th" = "No" ]

(2) 对于 部分if [ "$th" = "yes" ] || [ "$th" = "Yes" ];,您需要扩展此代码块以包含直到测试 for 为止的所有内容,并在此时No使用来将其组合为一个更大的复合语句。elifif-elif-fi

这是上面提到的更正:

echo -n “你渴吗?”

if [ "$th" = "是" ] || [“$th”=“是”];然后

    回声:“你想喝点什么?”

    如果[“$th”=“水”];然后
      echo“清脆爽口”。
    elif [ "$th" = "啤酒" ];然后
      echo“让我看一下身份证。”
    elif [ "$th" = "酒" ];然后
      echo “一盒还是两盒?”
    别的
      echo “马上就来。”

elif [ "$th" = "否" ] || [“$th”=“否”];然后
    echo “渴了就回来吧。”

相关内容