How to save & restore all shell options including errexit

What you're doing should work. But bash turns off the errexit option in command substitutions, so it preserves all the options except this one. This is specific to bash and specific to the errexit option. Bash does preserve errexit when running in POSIX mode. Since bash 4.4, bash also doesn't clear errexit in a command substitution if shopt -s inherit_errexit is in effect.

Since the option is turned off before any code runs inside the command substitution, you have to check it outside.

OLDOPTS=$(set +o)
case $- in
  *e*) OLDOPTS="$OLDOPTS; set -e";;
  *) OLDOPTS="$OLDOPTS; set +e";;
esac

If you don't like this complexity, use zsh instead.

setopt local_options

After trying old of the above on alpine 3.6, I've now taken the following much simpler approach:

OLDOPTS="$(set +o); set -${-//c}"
set -euf -o pipefail

... my stuff

# restore original options
set +vx; eval "${OLDOPTS}"

as per documentation, "$-" holds the list of currently active options. Seems to work great, am I missing anything?

Tags:

Shell

Bash