【发布时间】:2020-06-08 21:43:07
【问题描述】:
假设我有一个类似于以下内容的命令:
VAR=$(python SomeScript | tee /dev/null)
我想获取 python 脚本的退出代码,但不确定如何在同一命令中分配。
【问题讨论】:
-
tee /dev/null太没用了,你想用这个做什么?
标签: python bash pipe exit-code
假设我有一个类似于以下内容的命令:
VAR=$(python SomeScript | tee /dev/null)
我想获取 python 脚本的退出代码,但不确定如何在同一命令中分配。
【问题讨论】:
tee /dev/null 太没用了,你想用这个做什么?
标签: python bash pipe exit-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
如果您需要提取多个退出状态,则必须将它们写入文件 或流的末尾,然后再读回或提取它们。
【讨论】:
像这样:
var="$(python SomeScript)" >/dev/null
echo "SomeScript exit code: $?"
【讨论】: