This can actually be done with a single line using the set builtin command with the -e option.
#1------------------------------------------------------------------------
# exit when any command fails
#Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.
set -e
#all other commands
#2------------------------------------------------------------------------
#Other fancy way, by keeping the track of each command
# exit when any command fails
set -e
# 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
#3---------------------------------------------------------------------
#With a subs
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