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

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

问题描述

我正在尝试编写一个脚本,该脚本将读取两个选项,如果两个选项均为 y,我希望它说 Test Done!。如果它们中的一个或两个都不是 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',因此程序可以正确打印测试完成!

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天全站免登陆