如果任何命令返回非零值,则中止 shell 脚本 [英] Aborting a shell script if any command returns a non-zero value

查看:37
本文介绍了如果任何命令返回非零值,则中止 shell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用许多命令的 Bash shell 脚本.

I have a Bash shell script that invokes a number of commands.

如果任何命令返回非零值,我希望 shell 脚本自动退出,返回值为 1.

I would like to have the shell script automatically exit with a return value of 1 if any of the commands return a non-zero value.

如果不明确检查每个命令的结果,这可能吗?

Is this possible without explicitly checking the result of each command?

例如

dosomething1
if [[ $? -ne 0 ]]; then
    exit 1
fi

dosomething2
if [[ $? -ne 0 ]]; then
    exit 1
fi

推荐答案

将此添加到脚本的开头:

Add this to the beginning of the script:

set -e

如果一个简单的命令以非零退出值退出,这将导致 shell 立即退出.简单命令是不属于 if、while 或 until 测试或 && & 部分的任何命令.或 ||清单.

This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.

请参阅set"内部命令上的 bash(1) 手册页了解更多详情.

See the bash(1) man page on the "set" internal command for more details.

我个人以set -e"开始几乎所有的shell脚本.当中间出现故障并破坏脚本其余部分的假设时,让脚本顽固地继续下去真的很烦人.

I personally start almost all shell scripts with "set -e". It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script.

这篇关于如果任何命令返回非零值,则中止 shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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