Exit a Script On Error

后端 未结 5 748
温柔的废话
温柔的废话 2021-01-30 04:53

I\'m building a Shell Script that has a if function like this one:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
            


        
5条回答
  •  攒了一身酷
    2021-01-30 05:14

    If you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

    #!/bin/bash
    f () {
        errorCode=$? # save the exit code as the first thing done in the trap function
        echo "error $errorCode"
        echo "the command executing at the time of the error was"
        echo "$BASH_COMMAND"
        echo "on line ${BASH_LINENO[0]}"
        # do some error handling, cleanup, logging, notification
        # $BASH_COMMAND contains the command that was being executed at the time of the trap
        # ${BASH_LINENO[0]} contains the line number in the script of that command
        # exit the script or return to try again, etc.
        exit $errorCode  # or use some other value or do return instead
    }
    trap f ERR
    # do some stuff
    false # returns 1 so it triggers the trap
    # maybe do some other stuff
    

    Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals RETURN and DEBUG.

提交回复
热议问题