Hacker News new | ask | show | jobs
by embolalia 4352 days ago
Better than set -e is trapping ERR. You can set up a trap that prints out the command that failed, and the line it's on, rather than just dying quietly like set -e does. It's much easier to debug that than trying to work ahead from the last command with output. For bonus points, when you have a bunch of scripts together, put the trap code in its own file and source it in all the other scripts (rather than duplicating code).
2 comments

Example usage with backtrace:

    set -o errtrace
    trap 'err_handler $?' ERR

    err_handler() {
      trap - ERR
      let i=0 exit_status=$1
      echo "Aborting on error $exit_status:"
      echo "--------------------"
      while caller $i; do ((i++)); done
      exit $?
    }
It's also amazing that you can trap SIGTERM to perform clean-up tasks when the user Ctrl-Cs a script.
That would be SIGINT - SIGTERM is sent when you kill the process without specifying a specific signal to send, or when the system is shutting down.