Skip to content

Instantly share code, notes, and snippets.

@dreness
Created February 11, 2018 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreness/e9d4a93957962209706fe5c44218e56d to your computer and use it in GitHub Desktop.
Save dreness/e9d4a93957962209706fe5c44218e56d to your computer and use it in GitHub Desktop.
a few bash techniques for error handling
#!/usr/bin/bash
trap "echo inner ERR" ERR
trap "echo inner EXIT" EXIT
aThunk()
{
unsurprisingly
}
doIts()
{
aThunk | cat ; echo "dollar zero: $?"
echo $very
aThunk | obviously ; echo "dollar zero: $?"
echo $thisIs theEnd
}
doIts
#!/usr/bin/bash
trap "echo outter ERR" ERR
trap "echo outter EXIT" EXIT
setMode()
{
echo set "$*"
eval set "$*"
export SHELLOPTS
}
DEFAULTS=$(set +o)
MODES=("-o pipefail" "-u" "-e" "-Ee")
echo "baseline (default options) "
./funcs.sh ; echo ''
for i in `seq 1 ${#MODES[@]}`;
do
echo -n "Test $i: "
setMode ${MODES[$i-1]}
./funcs.sh || true
echo ''; eval ${DEFAULTS}; export SHELLOPTS
done
@dreness
Copy link
Author

dreness commented Feb 11, 2018

Looks like:

$ ./test.sh
baseline (default options)
./funcs.sh: line 8: unsurprisingly: command not found
dollar zero: 0

./funcs.sh: line 15: obviously: command not found
./funcs.sh: line 8: unsurprisingly: command not found
dollar zero: 127
theEnd
inner EXIT

Test 1: set -o pipefail
./funcs.sh: line 8: unsurprisingly: command not found
dollar zero: 127

./funcs.sh: line 15: obviously: command not found
./funcs.sh: line 8: unsurprisingly: command not found
dollar zero: 127
theEnd
inner EXIT

Test 2: set -u
./funcs.sh: line 8: unsurprisingly: command not found
dollar zero: 127
./funcs.sh: line 14: very: unbound variable
inner EXIT

Test 3: set -e
./funcs.sh: line 8: unsurprisingly: command not found
inner EXIT

Test 4: set -Ee
./funcs.sh: line 8: unsurprisingly: command not found
inner ERR
inner ERR
inner EXIT

outter EXIT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment