Se você deseja lidar com um erro em vez de sair às cegas, em vez de usar set -e
, use a trap
no ERR
pseudo sinal.
#!/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
Outras armadilhas podem ser configuradas para lidar com outros sinais, incluindo os sinais usuais do Unix mais os outros pseudo-sinais do Bash RETURN
e DEBUG
.