Use a bash trap in a script, see the example below bash script:
#!/usr/bin/bash main() { trap 'error_handler ${LINENO} $?' ERR ###### put your commands in the following echo "START" non_existent_command echo "END" } error_handler() { process="$0" lastline="$1" lasterr="$2" printf 'ERROR: %s: line %s: last command exit status: %s \n' "$process" "$lastline" "$lasterr" trap - ERR exit 0 } main
if you try to run a nonexistent command ( non_existent_command
in the example) or a command with an exit status other than 0, the trap activates the error_handler
function, which contains the exit exit 0
. In the above example, the output would be:
>START >./new.sh: line 8: non_existent_command: command not found >ERROR: ./new.sh: line 8: last command exit status: 127
Please note that βSTARTβ is printed, but βENDβ is not.
source share