代码之家  ›  专栏  ›  技术社区  ›  natevw

如果命令失败,从stdout*或*回退设置shell变量

  •  0
  • natevw  · 技术社区  · 7 年前

    我的脚本调用外部命令(例如。 readlink )这将:

    我知道如何单独执行每项操作,例如捕获我可以使用的标准输出

    MY_VAR=$(readlink /)
    

    if readlink /tmp; then
       echo "Success"
    fi
    

    if MY_VAL=`readlink "$MY_ARG"`; then
        echo "Value is ${MY_VAL}"
    else
        echo "Not found"
    fi
    

    更新 :所以我试了一下,结果成功了

    set -e 指定,即如果其他命令返回错误,则整个脚本将失败。首选通用shell,除非bash有更好的机制。

    3 回复  |  直到 7 年前
        1
  •  4
  •   KamilCuk    7 年前

    只是:

    if MY_VAR=$(readlink /); then
       echo "Success"
    fi
    

    $(true; false;)

     a=$(true)$(false)
    

    将始终返回非零返回状态。但是:

     a=$(false)$(true)
    

    将返回零返回状态,因为最后执行的命令替换命令为 true 返回零状态。

    if var=$(...); then 它允许在保存命令的标准输出时检查命令的返回状态。

    $( .. ) 但是可读性较差,不能嵌套,并且 deprecated .

        2
  •  0
  •   Mehdi Bahra    7 年前

        3
  •  0
  •   natevw    7 年前

    所以我的“希望它能像这个例子那样工作”

    if MY_VAL=$(readlink "$MY_ARG"); then
        echo "Value is ${MY_VAL}"
    else
        echo "Not found"
    fi
    

    原因是这样的变量赋值的“退出代码” is the exit code of the command inside . 变量赋值发生

    推荐文章