shell - 通过逻辑 && 和 || 表达 If then else

标签 shell if-statement ksh conditional-statements logical-operators

我正在尝试建立使用逻辑 && 和 || 的等效性运算符到“If then else fi”条件,我想验证这种理解是否正确。 考虑这个 if 条件,与我的相关

if ( flag="$value" ) then 
function1 ( p1) 
rc=$?
    if ( "$rc"=0 ) then 
    function2 ( p2)
    fi
elif (flag="$value2" ) then
function1 ( p1) 
rc=$?
    if ( "$rc"=0 ) then 
    function2 ( p2)
    fi
else 
echo "Msg"
fi

写成逻辑&&和||作为

 ( ( [ flag = "$value" ] && function1 (p1) ) && function2 (p2) ) || 
   ( ( [ flag = "$value2" ] && function1 (p2) ) && function2 (p2)) || 
    echo "message" 

我的问题是:

  • 上面的方法可以一直使用吗?有哪些注意事项和“注意事项”
  • 在其他地方有一些关于 () 括号旋转的新 shell 的讨论,该 shell 的变量对父级不可用。我想看看如何将这些运算符分组以指示优先级,如果不是那些 () 括号。

@切普纳。感谢您的澄清。 所以在一个看起来像这样的案例陈述中

optf=false
opte=false
optp=false

case $opt in

  p ) ...
     (( $opte || $optf ) && [ -n "$s1" ] ) && echo "error message" 

上面可以改写为

 {{ $opte || $optf } ; && [ -n "$s1" ] ; } && echo "error message" 

它会这样翻译这个逻辑:当你遇到 p 选项时,检查 opte 或 optf 是否为真。如果任一为真并且 s1 有值,则抛出错误消息。 会不会是这样,要不,还有一些坑要堵。 明白了——我没有注意到“;” .和 { } ; - 我应该能够以我想要的方式加入我的运营商?

最佳答案

注意

if command1; then
    command2
else
    command3
fi

不等同于 command1 && command2 ||命令 3.

  • 如果 command1 失败,将跳过 command2 并按预期运行 command3
  • 如果 command1 成功,并且 command2 运行并成功command3 将按预期跳过。<
  • 如果 command1 成功,而 command2 运行失败,则运行 command3,这与 if 语句。

你需要使用类似的东西:

command1 && { command2; true; } || command3

这将强制 && 的右侧操作数成功,而不管 command2 是否成功,因此永远不会运行 command3command1 成功时。

关于shell - 通过逻辑 && 和 || 表达 If then else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21913513/

相关文章:

java - 需要从java执行shell脚本

.net - 从 .NET 应用程序执行 shell 命令

java - 在Java中连续移动图像

CS50 PSet 2 - Vigenere - 确保关键字按字母顺序排列

linux - 更智能、更简洁的方法来匹配 shell 脚本中的输入变量?

linux - 如何在大文件中查找唯一行?

linux - 从另一个脚本运行 bash 脚本而不等待脚本完成执行?

javascript - "If"合并/避免嵌套

bash - 将列表转为表格格式 (awk)

linux - 对特定的日期列进行排序并获取最早的日期