在Shell脚本中捕获失败命令的退出状态 [英] Capturing exit status of a failed command in a shell script

查看:94
本文介绍了在Shell脚本中捕获失败命令的退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下多个命令的shell脚本

I have a shell script with multiple commands as below

cmd-1
cmd-2
cmd-3
....
cmd-n

我希望即使中间出现故障,例如cmd-3或cmd-7,shell脚本的执行也要继续.为了达到这个目的,我使用了set + e.这使我可以继续执行,但是我无法捕获失败命令的退出状态(因为脚本的退出状态始终基于最后一条命令).有什么方法可以根据上一个失败的命令来设置完整脚本的状态.

I want the shell script execution to continue even if there is a failure in the middle e.g cmd-3 or cmd-7. To achieve this I used set +e. This allows me to continue the execution, but I am unable to capture the exit status of the failed command (since exit status of the script is always based on the last command). Is there any way to set the status of the complete script based on last failed command.

推荐答案

您可以这样实现.不太干净,但是很容易.

You can achieve it like that. Not too clean way, but quite easy.

exit_code=0
cmd-1 || exit_code=$?
cmd-2 || exit_code=$?
cmd-3 || exit_code=$?
....
cmd-n || exit_code=$?
exit $exit_code

干净的方法是将代码拆分为函数,然后在此处检查命令结果.

The clean way would be to split your code to functions and check result of you commands there.

这篇关于在Shell脚本中捕获失败命令的退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆