Si desea poder gestionar un error en lugar de salir a ciegas, en lugar de utilizar set -e
, utilice un trap
en la pseudo señal ERR
.
#!/bin/bash
f() {
errcode=$? # 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 $errcode # 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
Otras trampas se pueden configurar para manejar otras señales, incluyendo las señales de Unix usuales y las otras señales seudo Bash RETURN
y DEBUG
.
Si te gusta el ABS, te encantará la [BashGuide] (http://mywiki.wooledge.org/BashGuide), [BashFAQ] (http://mywiki.wooledge.org/BashFAQ) y [BashPitfalls] (http://mywiki.wooledge.org/BashPitfalls). –