Skip to content

Instantly share code, notes, and snippets.

@dreness dreness/funcs.sh
Created Feb 11, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.