Skip to content

Instantly share code, notes, and snippets.

@dtroyer
Last active September 19, 2019 15:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dtroyer/a065b77ebe0443659898 to your computer and use it in GitHub Desktop.
Save dtroyer/a065b77ebe0443659898 to your computer and use it in GitHub Desktop.
Test traps, errexit, errtrace
#!/bin/bash
# Do some errexit testing
# 0 - test success
# 1 - test simple fail
# 2 - test function fail
#
# in function
# N errexit errtrace pass?
# 2 Y N Y
# 3 Y Y Y
# 4 N N N
# 5 N Y Y
# in subshell
# N errexit errtrace pass?
# 6 Y N Y
# 7 Y Y Y
# 8 N N Y
# 9 N Y Y
# Make a scenario selection
N=${1:-0}
FALSE=./false.sh
set -o errexit
set -o xtrace
# Set up traps like stack.sh does
trap exit_trap EXIT
function exit_trap {
local r=$?
if [[ $r -ne 0 ]]; then
echo "Error on exit"
fi
echo "Leaving exit_trap: $r"
exit $r
}
trap err_trap ERR
function err_trap {
local r=$?
set +o xtrace
echo "Leaving err_trap: $r"
exit $r
}
fail_function() {
false
echo "Should never be displayed"
}
case $N in
0) # simple success
true
;;
1) # simple top-level error
false
;;
2) # fail in function
fail_function
echo "FAIL"
;;
3) # fail in function with -E
set -o errtrace
fail_function
echo "FAIL"
;;
4) # fail in function without errexit
set +o errexit
fail_function
echo "FAIL"
;;
5) # fail in function with -E without errexit
set +o errexit
set -o errtrace
fail_function
echo "FAIL"
;;
6) # fail in subshell
bash -c ${FALSE}
echo "FAIL"
;;
7) # fail in subshell with -E
set -o errtrace
bash -c ${FALSE}
echo "FAIL"
;;
8) # fail in subshell without errexit
set +o errexit
bash -c ${FALSE}
echo "FAIL"
;;
9) # fail in subshell with -E without errexit
set +o errexit
set -o errtrace
bash -c ${FALSE}
echo "FAIL"
;;
esac
# Record reaching the end of the script
echo "Fini"
#!/bin/bash
# not strictly necessary as bash -c false has same effect
false
for i in `seq 0 9`; do echo "N=$i"; ./test-errexit $i; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment