Aborting a shell script if any command returns a n

2019-01-05 06:59发布

I have a Bash shell script that invokes a number of commands. 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?

e.g.

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

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

9条回答
成全新的幸福
2楼-- · 2019-01-05 07:29

If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:

# Create the trap with   
#    trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah

Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-05 07:38

Run it with -e or set -e at the top.

Also look at set -u.

查看更多
乱世女痞
4楼-- · 2019-01-05 07:39

just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:

[[ `cmd` ]] && echo success_else_silence

which is the same as cmd || exit errcode as someone showed.

eg. I want to make sure a partition is unmounted if mounted:

[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1 
查看更多
登录 后发表回答