proper way to detect shell exit code when errexit option set

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

提交回复
热议问题