首页 > 解决方案 > 从分配中的多个命令中获取退出代码

问题描述

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

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

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

标签: pythonbashpipeexit-code

解决方案


如果您只有一个退出代码要返回,您可以提取并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

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


推荐阅读