如何判断bash脚本中的任何命令是否失败(退出状态为非零) [英] How to tell if any command in bash script failed (non-zero exit status)

查看:840
本文介绍了如何判断bash脚本中的任何命令是否失败(退出状态为非零)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道bash脚本中的任何命令是否以非零状态退出.

I want to know whether any commands in a bash script exited with a non-zero status.

我想要类似于set -e功能的东西,除了我不希望它以非零状态退出时退出.我希望它运行整个脚本,然后我想知道其中一个:

I want something similar to set -e functionality, except that I don't want it to exit when a command exits with a non-zero status. I want it to run the whole script, and then I want to know that either:

a)所有退出状态为0的命令
-或-
b)以非零状态退出的一个或多个命令

a) all commands exited with exit status 0
-or-
b) one or more commands exited with a non-zero status


例如,给出以下内容:


e.g., given the following:

#!/bin/bash

command1  # exits with status 1
command2  # exits with status 0
command3  # exits with status 0

我希望所有三个命令都运行.运行脚本后,我希望指示至少有一个命令以非零状态退出.

I want all three commands to run. After running the script, I want an indication that at least one of the commands exited with a non-zero status.

推荐答案

在ERR上设置陷阱:

#!/bin/bash

err=0
trap 'err=1' ERR

command1
command2
command3
test $err = 0 # Return non-zero if any command failed

您甚至可以进行一些自省以获取有关错误发生位置的数据:

You might even throw in a little introspection to get data about where the error occurred:

#!/bin/bash
for i in 1 2 3; do
        eval "command$i() { echo command$i; test $i != 2; }"
done

err=0
report() {
        err=1
        echo -n "error at line ${BASH_LINENO[0]}, in call to "
        sed -n ${BASH_LINENO[0]}p $0
} >&2
trap report ERR

command1
command2
command3
exit $err

这篇关于如何判断bash脚本中的任何命令是否失败(退出状态为非零)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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