yanivk1984
2/20/2020 - 1:09 PM

linux scripting - trap commands before exiting

# keep track of the last executed command
trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
# echo an error message before exiting
trap 'echo "\"${last_command}\" command filed with exit code $?."' EXIT

For example, if we run ls --fake-option then we’ll see an informative error message as follows.

ls: unrecognized option '--fake-option'
Try 'ls --help' for more information.
"ls --fake-option" command filed with exit code 2.

Exit Only When Specific Commands Fail
The global solution is often fine, but sometimes you only care if certain commands fail. We can handle this situation by defining a function that needs to be explicitly invoked to check the status code and exit if necessary.

exit_on_error() {
    exit_code=$1
    last_command=${@:2}
    if [ $exit_code -ne 0 ]; then
        >&2 echo "\"${last_command}\" command failed with exit code ${exit_code}."
        exit $exit_code
    fi
}

# enable !! command completion
set -o history -o histexpand