proper way to detect shell exit code when errexit option set

后端 未结 14 1506
甜味超标
甜味超标 2021-01-30 12:52

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

The following code will stop at bad_command line

#!/bin/b         


        
相关标签:
14条回答
  • 2021-01-30 13:23

    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.

    0 讨论(0)
  • 2021-01-30 13:23
    set -o errexit
    
    bad_command || {
      resp_code=$?
      echo Bad Thing $resp_code happened
    }
    
    0 讨论(0)
  • 2021-01-30 13:28

    Just trying to complete the following answer: https://stackoverflow.com/a/32201766/2609399 , which is a very good catch, BTW.

    I've faced this limitation a time ago and applied a similar fix for it. Please consider the below code sample.

    invokeBashFunction() {
      local functionExitCode="0"
      /bin/bash -c "
        set -o errexit
    
        ${*}
      " || functionExitCode="${?}"
    
      # add some additional processing logic/code
    
      return "${functionExitCode}"
    }
    export -f invokeBashFunction
    

    And there are few example of how to use it:

    invokeBashFunction bad_function param1 "param 2" param3 && echo "It passed." || echo "It failed!"
    
    if invokeBashFunction bad_function param1 "param 2" param3
    then
      echo "It passed."
    fi
    
    if ! invokeBashFunction bad_function param1 "param 2" param3
    then
      echo "It failed!"
    fi
    
    0 讨论(0)
  • 2021-01-30 13:28

    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

    0 讨论(0)
  • 2021-01-30 13:29

    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
    
    0 讨论(0)
  • 2021-01-30 13:35

    A clean reliable way to error exit

    command_that_error_exits || { echo "Line $LINENO: Failed with Error" 1>&2; exit 1;}
    
    0 讨论(0)
提交回复
热议问题