Robust Error Handling in Shell

Level 5246 keystrokes

set -euo pipefail makes the script stop on failed commands, unset variables and failures inside pipelines, and an ERR trap reports the failing line. A missing config.json is checked explicitly, so the script logs a message and exits. Timestamps vary.

Shell code

# Strict mode: -e stops on errors, -u on unset variables, pipefail on failures inside pipes
1set -euo pipefail
# Report the line number on stderr and exit with 1
2error_handler() {
3 echo "Error on line $1" >&2
4 exit 1
5}
# Single quotes delay $LINENO until the trap runs, so it is the failing line
6trap 'error_handler $LINENO' ERR
# Prefix each message with the time; $* joins all arguments
7log() { echo "[$(date +%H:%M:%S)] $*"; }
8log "Starting script"
# If config.json is missing, log and exit 1; a test inside || does not fire the ERR trap
9[[ -f config.json ]] || { log "Config missing"; exit 1; }
# Reached only when the config file exists
10log "Config loaded"

Output

[14:30:45] Starting script
[14:30:45] Config missing
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
  • $× 4
  • ;× 3
  • (× 3
  • )× 3
  • [× 3
  • ]× 3
  • {× 3
  • }× 3
  • %× 3

More Shell examples at level 5

← Shell typing practice