两个条件,如果(Two conditions in if)

2019-09-19 05:06发布

我试图写一个脚本,将读取两种选择,如果他们都将是“Y”我希望它说“测试完成!” 如果一方或双方不会是“Y”我希望它说:“测试失败!” 以下是我想出了:

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”它在说这两个问题“测试完成!” 我做了什么错?

Answer 1:

你检查错误条件。

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

上述声明是真实的,当choice!='y' ,并choice1!='y' ,所以程序正确打印“测试完成!”

该修正后的脚本是

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


Answer 2:

该方案是做什么你告诉它做的事。 你说:“如果第一志愿不等于‘Y’和第二志愿不等于‘Y’然后打印‘测试完成’,否则打印‘测试失败’ - !所以只有两个选择并不 ÿ意志“测试完成!”被打印出来。

你大概的意思是:

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

我变!=不等于==等号。 现在,只要你回答“是”这两个问题将“测试完成!” 被打印。



Answer 3:

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


Answer 4:

你得到了比较逻辑倒退; 从你的描述,你想说的话

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

实际上,我惊讶的是,&&建设工程,虽然进一步检查。它可能应该。 不过,我会写为

if [ "$choice" = 'y' -a "$choice1" = 'y' ]; then


Answer 5:

你有你的逻辑颠倒; 你检查!=时,你应该检查==。 尝试这个:

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


Answer 6:

又一想,

$ c1='y' ; c2='y' ; [[ ${c1} = 'y' ]] && [[ ${c2} = 'y' ]] && echo true || echo false  
true  
$ c1='n' ; c2='y' ; [[ ${c1} = 'y' ]] && [[ ${c2} = 'y' ]] && echo true || echo false  
false  
$ c1='n' ; c2='y' ; [[ ${c1} = 'y' ]] || [[ ${c2} = 'y' ]] && echo true || echo false  
true  
$ c1='n' ; c2='n' ; [[ ${c1} = 'y' ]] || [[ ${c2} = 'y' ]] && echo true || echo false  
false  
$  

乱码的溢出。 (;



Answer 7:

如果你尝试过什么

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


Answer 8:

这条线

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

如果两个选择ARENT“Y”,所以当这两个选择是“Y”,该声明是假的,你的程序正确打印“试验失败”试验



文章来源: Two conditions in if