如何在unix中使用IF循环来满足多种条件

时间:2014-06-04 11:54:08

标签: shell unix if-statement

我需要一个逻辑来在unix中实现以下逻辑

if ( $a !="xyz" || $d !="abc" ) && ( $b= $c))
then
echo "YES WORKING"
fi

我尝试了以下代码无效

if [ [ [ $a != "xyz" ] -o [ $d != "abc" ] ] -a [ "$b" = "$c" ] ]
then
echo "YES WORKING"
fi

错误

  

:[:]意外的操作符/操作数

2 个答案:

答案 0 :(得分:3)

您可以这样做:

[ $a != "xyz" -o $d != "abc" ] && [ "$b" = "$c" ] && echo "YES WORKING"

答案 1 :(得分:2)

在支持[[ ]]

的shell中,您的逻辑应该很容易
if [[ ($a != "xyz" || $d != "abc") && $b = "$c" ]]; then
    echo "YES WORKING"
fi

虽然对那些没有的人有一种方法:

if ([ ! "$a" = "xyz" ] || [ ! "$d" = "abc" ]) && [ "$b" = "$c" ]; then
    echo "YES WORKING"
fi

但是因为你要召唤子shell,所以效率仍然很低,所以使用{ }但语法有点难看:

if { [ ! "$a" = "xyz" ] || [ ! "$d" = "abc" ]; } && [ "$b" = "$c" ]; then
    echo "YES WORKING"
fi