Skip to main content
blog.philz.dev

Shell Trap

Should you fall into the trap of having a load bearing shell script, perhaps this will help:

set -euo pipefail
trap 'echo Error in $0 at line $LINENO: $(cd "'"${PWD}"'" && awk "NR == $LINENO" $0)' ERR

And then you can play three truths and a lie:

$cat /tmp/three-truths-and-a-lie.sh
#!/usr/bin/env bash
set -euo pipefail
trap 'echo Error in $0 at line $LINENO: $(cd "'"${PWD}"'" && awk "NR == $LINENO" $0)' ERR
true
true
true
false

$/tmp/three-truths-and-a-lie.sh
Error in /tmp/three-truths-and-a-lie.sh at line 7: false

My rule of thumb is that once you get to 100 lines of shell, it's time to move on.