proper way to detect shell exit code when errexit option set

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

    Continue to write solid shell code.

    You do it right if bad_command is really a command. But be careful with function calls in if, while, ||, && or !, because errexit will not work there. It may be dangerous.

    If your bad_command is actually bad_function you should write this:

    set -eu 
    
    get_exit_code() {
        set +e
        ( set -e;
          "$@"
        )
        exit_code=$?
        set -e
    }
    
    ...
    
    get_exit_code bad_function
    
    if [ "$exit_code" != 0 ]; then
        do_err_handle
    fi
    

    This works well in bash 4.0. In bash 4.2 you only get exit codes 0 or 1.

提交回复
热议问题