proper way to detect shell exit code when errexit option set

后端 未结 14 1515
甜味超标
甜味超标 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: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
    

提交回复
热议问题