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 failures1set -euo pipefail# Handler that describes a failed command2err_handler() { # Line number, command text and exit code passed by the trap3 local line=$1 cmd=$2 code=$34 echo "Error at line $line: '$cmd' exited with $code" >&25}# On ERR, pass the line, the failing command and its status ($?) to the handler6trap 'err_handler $LINENO "$BASH_COMMAND" $?' ERR# die: print a fatal message to stderr and exit with 17die() { echo "FATAL: $1" >&2; exit 1; }# config.txt is missing, so die runs; a test inside || does not fire the ERR trap8[[ -f config.txt ]] || die "Config not found"Output
FATAL: Config not found
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