stop a script on errors

Make a script stop at the first failing command, say where, and still allow the ones that may fail.

  • shell
  • development

Steps

  1. set -euo pipefail

    at the top: stop on errors (-e), on unset variables (-u), on failing pipes

  2. trap 'echo "failed at line $LINENO"' ERR

    say where it stopped

  3. command || { echo 'command failed'; exit 1; }

    stop with a message of your own

  4. command || true

    let this one fail

  5. if command; then echo ok; fi

    test whether it worked: $? is its exit code

Commands used

  • set
  • trap

Each has a page in lore: lore set opens it.