How to tell if any command in bash script failed (

2020-02-28 02:05发布

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

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) 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.

7条回答
2楼-- · 2020-02-28 02:46

For each command you could do this:

if ! Command1 ; then an_error=1; fi 

And repeat this for all commands

At the end an_error will be 1 if any of them failed.

If you want a count of failures set an_error to 0 at the beginning and do $((an_error++)). Instead of an_error=1

查看更多
登录 后发表回答