Error Handling in Shell

Level 5257 keystrokes

Strict mode stops the script on errors, an ERR trap reports the line, command and exit status of a failing command, and die prints a fatal message and exits. Since config.txt is missing, die prints "FATAL: Config not found".

Shell code

# Strict mode: exit on errors, unset variables and pipe failures
1set -euo pipefail
# Handler that describes a failed command
2err_handler() {
# Line number, command text and exit code passed by the trap
3 local line=$1 cmd=$2 code=$3
4 echo "Error at line $line: '$cmd' exited with $code" >&2
5}
# On ERR, pass the line, the failing command and its status ($?) to the handler
6trap 'err_handler $LINENO "$BASH_COMMAND" $?' ERR
# die: print a fatal message to stderr and exit with 1
7die() { echo "FATAL: $1" >&2; exit 1; }
# config.txt is missing, so die runs; a test inside || does not fire the ERR trap
8[[ -f config.txt ]] || die "Config not found"

Output

FATAL: Config not found
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • $× 10
  • "× 8
  • '× 4
  • _× 3
  • =× 3
  • -× 2
  • ;× 2
  • :× 2
  • (× 2
  • )× 2

More Shell examples at level 5

← Shell typing practice