bash 运行命令而不因错误退出并告诉我它的退出代码

Vla*_*nea 7 bash shell

我想从 bash 脚本运行一个可能失败的命令,将其退出代码存储在变量中,然后运行后续命令,而不管该退出代码如何。

我试图避免的例子:

使用set

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
Run Code Online (Sandbox Code Playgroud)

使用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
Run Code Online (Sandbox Code Playgroud)

有没有一种语义上简单的方法来告诉 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
Run Code Online (Sandbox Code Playgroud)

Eri*_*kMD 8

我相信你可以使用||运营商?这相当于“if \xe2\x88\x92 else”命令。

\n

以下内容可以解决您的用例吗?(否则请随意发表评论!)

\n
set -e  # implied in a CI context\nexit_status=0\ndocker exec "$CONTAINER_NAME" npm test || exit_status=$?\ndocker cp "$CONTAINER_NAME:/home/test/test-results.xml" .\nexit "$exit_status"\n
Run Code Online (Sandbox Code Playgroud)\n

或者更简单地说:

\n
set -e  # implied in a CI context\ndocker exec "$CONTAINER_NAME" npm test || exit_status=$?\ndocker cp "$CONTAINER_NAME:/home/test/test-results.xml" .\nexit "${exit_status:-0}"\n
Run Code Online (Sandbox Code Playgroud)\n

顺便说一句,如果您对此退出状态代码不感兴趣,您也可以执行以下操作:

\n
set -e  # implied in a CI context\ndocker exec "$CONTAINER_NAME" npm test || :\ndocker cp "$CONTAINER_NAME:/home/test/test-results.xml" .\n
Run Code Online (Sandbox Code Playgroud)\n

有关提示的更多详细信息|| :,请参阅 Unix-&-Linux SE 上的答案:
\n在 bash 脚本中哪个更惯用:|| true|| :

\n