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 pipes1set -euo pipefail# Report the line number on stderr and exit with 12error_handler() {3 echo "Error on line $1" >&24 exit 15}# Single quotes delay $LINENO until the trap runs, so it is the failing line6trap 'error_handler $LINENO' ERR# Prefix each message with the time; $* joins all arguments7log() { 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 trap9[[ -f config.json ]] || { log "Config missing"; exit 1; }# Reached only when the config file exists10log "Config loaded"Output
[14:30:45] Starting script [14:30:45] Config missing
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