bash if 语句中的两个条件 [英] Two conditions in a bash if statement

查看:50
本文介绍了bash if 语句中的两个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本来读取两个选项,如果它们都是y",我希望它说测试完成!"如果其中一个或两个不是y",我希望它说测试失败!"

I'm trying to write a script which will read two choices, and if both of them are "y" I want it to say "Test Done!" and if one or both of them isn't "y" I want it to say "Test Failed!"

这是我想出的:

echo "- Do You want to make a choice?"
read choice

echo "- Do You want to make a choice1?"
read choice1

if [ "$choice" != 'y' ] && [ "$choice1" != 'y' ]; then
    echo "Test Done!"
else
    echo "Test Failed!"
fi

但是当我用y"回答两个问题时,它说测试失败!"而不是测试完成!".当我用n"回答两个问题时,它表示测试完成!"

But when I answer both questions with "y" it's saying "Test Failed!" instead of "Test Done!". And when I answer both questions with "n" it's saying "Test Done!"

我做错了什么?

推荐答案

您正在检查错误的条件.

You are checking for the wrong condition.

if [ "$choice" != 'y' ] && [ "$choice1" != 'y' ];

上述语句在 choice!='y'choice1!='y' 时为真,因此程序正确打印 "Test Done!.

The above statement is true when choice!='y' and choice1!='y', and so the program correctly prints "Test Done!".

更正后的脚本是

echo "- Do You want to make a choice ?"
read choice

echo "- Do You want to make a choice1 ?"
read choice1

if [ "$choice" == 'y' ] && [ "$choice1" == 'y' ]; then
    echo "Test Done !"
else
    echo "Test Failed !"
fi

这篇关于bash if 语句中的两个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆