Created
April 8, 2020 15:53
-
-
Save zdennis/53de2c110a685436a0dd21e7c45567e8 to your computer and use it in GitHub Desktop.
Bash: checking shell errexit shell option inside function, disabling it, and then restoring it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Show how to check, save, restore the errexit shell option that is commonly set | |
# using "set -e". This is useful for functions that care about non-zero exit statuses | |
# and want to do something because of it such as a retry function. | |
set -eu | |
echo "Shell options: $-" | |
function f(){ | |
local restore_errexit=""; | |
if [[ -o errexit ]] ; then | |
restore_errexit="yes" | |
fi; | |
# Disable set -e because we rely on non-zero exit statuses for retrying | |
# commands below. | |
set +e | |
echo "shell options with errexit disabled: $-" | |
# whis command will fail | |
which an_unknown_command | |
# we wan | |
if [ $? -ne 0 ] ; then | |
echo "a failed command ran, yay!" | |
fi | |
# Re-enable set -e if it was previously turned on | |
if [[ -n "$restore_errexit" ]] ; then | |
set -e | |
fi; | |
echo "shell options with errexit restored': $-" | |
} | |
f; | |
echo "Shell options: $-" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment