brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: trap ERR with $LINENO tells you which line of a shell script failed

Shell
~/tips/tip-shell-trap-err-lineno

trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR

Prints the line number and command when a bash script hits an error.

A script that dies with no message costs me more time than any bug in it.

set -Eeuo pipefail
trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR

The ERR trap runs when a command fails. $LINENO is the line and $BASH_COMMAND is the command that was running. -E makes functions and subshells inherit the trap, otherwise it only fires in the main script body. The trap does not fire for failures that if or && already handle. This is bash syntax, and zsh handles error traps differently.

Further reading: Bash manual: trap

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link