proper way to detect shell exit code when errexit

2019-03-08 13:50发布

I prefer to write solid shell code, so the errexit & nounset is alway set.

The following code will stop at bad_command line

#!/bin/bash
set -o errexit ; set -o nounset
bad_command # stop here
good_command

I want to capture it, here is my method

#!/bin/bash
set -o errexit ; set -o nounset
rc=1
bad_command && rc=0 # stop here
[ $rc -ne 0 ] && do_err_handle
good_command

Is there any better or cleaner method

My Answer:

#!/bin/bash
set -o errexit ; set -o nounset
if ! bad_command ; then
  # error handle here
fi
good_command

标签: shell
11条回答
男人必须洒脱
2楼-- · 2019-03-08 14:19

I cobbled together a (hopefully) textbook example from all the answers:

#!/usr/bin/env bash

# exit immediately on error
set -o errexit

file='dfkjlfdlkj'
# Turn off 'exit immediately on error' during the command substitution
blah=$(set +o errexit && ls $file) && rc=$? || rc=$?
echo $blah
# Do something special if $rc
(( $rc )) && echo failure && exit 1
echo success
查看更多
我命由我不由天
3楼-- · 2019-03-08 14:20

Keep with errexit. It can help find bugs that otherwise might have unpredictable (and hard to detect) results.

#!/bin/bash
set -o errexit ; set -o nounset

bad_command || do_err_handle
good_command

The above will work fine. errexit only requires that the line pass, as you do with the bad_command && rc=0. Therefore, the above with the 'or' will only run do_err_handle if bad_command fails and, as long as do_err_handle doesn't also 'fail', then the script will continue.

查看更多
Summer. ? 凉城
4楼-- · 2019-03-08 14:22

In bash you can use the trap builtin which is quite nice. See https://unix.stackexchange.com/questions/79648/how-to-trigger-error-using-trap-command

Not sure how portable it is with other shells.. so YMMV

查看更多
神经病院院长
5楼-- · 2019-03-08 14:23

Agree with comments, so if you can give up errexit then you can easily shorten your code to

 bad_command || do_err_handle
 good_command

I hope this helps.

查看更多
Luminary・发光体
6楼-- · 2019-03-08 14:24

what if you want to know exit status of bad_command?

I think the simplest way is to disable errexit:

#!/bin/sh
set -o errexit

some_code_here

set +o errexit
bad_command
status=$?
set -o errexit
process $status
查看更多
登录 后发表回答