Return an exit code without closing shell

前端 未结 5 1091
后悔当初
后悔当初 2021-01-01 12:39

I\'d like to return an exit code from a BASH script that is called within another script, but could also be called directly. It roughly looks like this:

#!/b         


        
5条回答
  •  醉酒成梦
    2021-01-01 12:47

    The answer to the question title (not in the body as other answers have addressed) is:

    Return an exit code without closing shell

    (exit 33)
    

    If you need to have -e active and still avoid exiting the shell with a non-zero exit code, then do:

    (exit 33) && true
    

    The true command is never executed but is used to build a compound command that is not exited by the -e shell flag.

    That sets the exit code without exiting the shell (nor a sourced script).

    For the more complex question of exiting (with an specific exit code) either if executed or sourced:

    #!/bin/bash
    [ "$BASH_SOURCE" == "$0" ] &&
        echo "This file is meant to be sourced, not executed" && 
            exit 30
    
    return 88
    

    Will set an exit code of 30 (with an error message) if executed.
    And an exit code of 88 if sourced. Will exit both the execution or the sourcing without affecting the calling shell.

提交回复
热议问题