Skip to content

Instantly share code, notes, and snippets.

@zdennis
Created April 8, 2020 15:53
Show Gist options
  • Save zdennis/53de2c110a685436a0dd21e7c45567e8 to your computer and use it in GitHub Desktop.
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.
#!/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