sh AND 和 OR 在一个命令中

ter*_*cow 9 shell shell-script test

试图在一行代码中检查 3 个条件,但我被卡住了。

本质上,我需要为以下内容编码:

如果

string1 不等于 string2

string3 不等于 string4

或者

bool1 = 真

然后

显示“条件满足 - 运行代码...”。

根据评论中的要求,我更新了我的示例以尝试使问题更清晰。

#!/bin/sh

string1="a"
string2="b"
string3="c"
string4="d"
bool1=true

# the easy-to-read way ....
if [ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] ; then
    echo "conditions met - running code ..."
fi

if $bool1 ; then
    echo "conditions met - running code ..."
fi

# or the shorter way ...
[ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] && echo "conditions met - running code ..."

$bool1 && echo "conditions met - running code ..."
Run Code Online (Sandbox Code Playgroud)

上面的代码可能会运行两次:如果满足前两个条件,然后如果满足第三个条件,则再次运行。这不是我需要的。

此示例的问题在于它涉及对 'echo' 的 2 个不同调用 - (注意:在实际代码中,它不是回声,但您明白了)。我试图通过将 3 个条件检查组合成一个命令来减少代码重复。

我敢肯定,现在有一些人摇头,对着屏幕大喊“你不是这样干的!”

可能还有其他人等待将其标记为重复......好吧,我看了,但如果我能从我读过的答案中弄清楚如何做到这一点,我就该死了。

有人可以启发我吗?:)

Fru*_*uit 12

这将起作用:

if    [ "$string1" != "$string2" ] \
   && [ "$string3" != "$string4" ] \
   || [ "$bool1" = true ]; then
    echo "conditions met - running code ...";
fi;
Run Code Online (Sandbox Code Playgroud)

或环绕以{ ;}提高可读性并便于将来维护。

if { [ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] ;} \
   || [ "$bool1" = true ] ; then
    echo "conditions met - running code ...";
fi;
Run Code Online (Sandbox Code Playgroud)

注意事项:

  1. 没有布尔变量这样的东西。.
  2. 大括号需要最后的分号 ( { somecmd;})
  3. &&并在上面从左到右||评估-比仅在具有更高的优先级&&|| (( ))[[..]]

&&更高的优先级只发生在[[ ]]如下证明。假设bool1=true

[[ ]]

bool1=true
if [[ "$bool1" == true || "$bool1" == true && "$bool1" != true ]]; then echo 7; fi #1 # Print 7, due to && higher precedence than ||
if [[ "$bool1" == true ]] || { [[ "$bool1" == true && "$bool1" != true ]] ;}; then echo 7; fi # Same as #1
if { [[ "$bool1" == true || "$bool1" == true ]] ;} && [[ "$bool1" != true ]] ; then echo 7; fi # NOT same as #1
if [[ "$bool1" != true && "$bool1" == true || "$bool1" == true ]]; then echo 7; fi # Same result as #1, proved that #1 not caused by right-to-left factor, or else will not print 7 here
Run Code Online (Sandbox Code Playgroud)

[ ]

bool1=true
if [ "$bool1" == true ] || [ "$bool1" == true ] && [ "$bool1" != true ]; then echo 7; fi #1, no output, due to && IS NOT higher precedence than ||
if [ "$bool1" == true ] || { [ "$bool1" == true ] && [ "$bool1" != true ] ;}; then echo 7; fi # NOT same as #1
if { [ "$bool1" == true ] || [ "$bool1" == true ] ;} && [ "$bool1" != true ]; then echo 7; fi # Same as #1
if [ "$bool1" != true ] && [ "$bool1" == true ] || [ "$bool1" == true ]; then echo 7; fi # Proved that #1 not caused by || higher precedence than &&, or else will not print 7 here, instead #1 is only left-to-right evaluation
Run Code Online (Sandbox Code Playgroud)