Si desea poder manejar un error en lugar de salir a ciegas, en lugar de usar set -e
, use a trap
en la ERR
pseudo señal.
#!/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
Se pueden configurar otras trampas para manejar otras señales, incluidas las señales habituales de Unix más las otras pseudo señales RETURN
y Bash DEBUG
.