【问题标题】:Getting exit code out of multiple commands in an assignment从分配中的多个命令中获取退出代码
【发布时间】:2020-06-08 21:43:07
【问题描述】:

假设我有一个类似于以下内容的命令:

VAR=$(python SomeScript | tee /dev/null)

我想获取 python 脚本的退出代码,但不确定如何在同一命令中分配。

【问题讨论】:

  • tee /dev/null 太没用了,你想用这个做什么?

标签: python bash pipe exit-code


【解决方案1】:

如果您只有一个退出代码要返回,您可以提取并使用它exit 以使其成为整个命令替换的退出代码:

var=$(
  python -c 'import sys; print("hi"); sys.exit(42)' | cat
  exit "${PIPESTATUS[0]}"
)
ret=$?
echo "The output is $var and the exit code is $ret"

这会导致:

The output is hi and the exit code is 42

如果您需要提取多个退出状态,则必须将它们写入文件 或流的末尾,然后再读回或提取它们。

【讨论】:

    【解决方案2】:

    像这样:

    var="$(python SomeScript)" >/dev/null
    echo "SomeScript exit code: $?"
    

    【讨论】:

      猜你喜欢
      • 2012-01-05
      • 2018-11-04
      • 2013-01-01
      • 2021-12-04
      • 2011-06-28
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多