我想从 bash 脚本运行一个可能会失败的命令,将其退出代码存储在一个变量中,然后运行后续命令而不考虑该退出代码。
我试图避免的例子:
使用设置
:
set +e # disable exit on error (it was explicitly enabled earlier)
docker exec $CONTAINER_NAME npm test
test_exit_code=$? # remember exit code of previous command
set -e # enable exit on error
echo "copying unit test result file to host"
docker cp $CONTAINER_NAME:/home/test/test-results.xml .
exit $test_exit_code
使用if
:
if docker exec $CONTAINER_NAME npm test ; then
test_exit_code=$?
else
test_exit_code=$?
fi
echo "copying unit test result file to host"
docker cp $CONTAINER_NAME:/home/test/test-results.xml .
exit $test_exit_code
是否有语义上直接的方式告诉 bash“运行命令而不退出错误,并告诉我它的退出代码”?
我的最佳选择仍然令人困惑,需要注释来向后续开发人员解释(这只是一个更简洁的 if/else):
docker exec $CONTAINER_NAME npm test && test_exit_code=$? || test_exit_code=$?
echo "copying unit test result file to host"
docker cp $CONTAINER_NAME:/home/test/test-results.xml .
exit $test_exit_code
最佳答案
我相信您可以只使用 ||
运算符?这相当于一个“if - else”命令。
以下内容是否可以解决您的用例? (否则请随时发表评论!)
set -e # implied in a CI context
exit_status=0
docker exec "$CONTAINER_NAME" npm test || exit_status=$?
docker cp "$CONTAINER_NAME:/home/test/test-results.xml" .
exit "$exit_status"
或更简单地说:
set -e # implied in a CI context
docker exec "$CONTAINER_NAME" npm test || exit_status=$?
docker cp "$CONTAINER_NAME:/home/test/test-results.xml" .
exit "${exit_status:-0}"
顺便说一句,如果你对这个退出状态码不感兴趣,你也可以这样做:
set -e # implied in a CI context
docker exec "$CONTAINER_NAME" npm test || :
docker cp "$CONTAINER_NAME:/home/test/test-results.xml" .
有关的更多详细信息|| :
提示,参见例如这个关于 Unix-&-Linux SE 的答案:
Which is more idiomatic in a bash script: || true
or || :
?
关于bash 运行命令而不退出错误并告诉我它的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69328221/