Use a RETURN trap
Commands specified with an RETURN trap are executed before execution resumes after a shell function ... returns...
The -p
option [to shopt] causes output to be displayed in a form that may be reused as input.
– https://www.gnu.org/software/bash/manual/bash.html
foobar() {
trap "$(shopt -p extglob)" RETURN
shopt -s extglob
# ... your stuff here ...
}
For test
foobar() {
trap "$(shopt -p extglob)" RETURN
shopt -s extglob
echo "inside foobar"
shopt extglob # Display current setting for errexit option
}
main() {
echo "inside main"
shopt extglob # Display current setting for errexit option
foobar
echo "back inside main"
shopt extglob # Display current setting for errexit option
}
Test
$ main
inside main
extglob off
inside foobar
extglob on
back inside main
extglob off
Variation: To reset all shopt options, change the trap statement to:
trap "$(shopt -p)" RETURN
Variation: To reset all set options, change the trap statement to:
trap "$(set +o)" RETURN
Note: Starting with Bash 4.4, there's a better way: make $- local.
Variation: To reset all set and all shopt options, change the trap statement to:
trap "$(set +o); $(shopt -p)" RETURN
NOTE: set +o
is equivalent to shopt -p -o
:
+o Write the current option settings to standard output in a format that is suitable for reinput to the shell as commands that achieve the same options settings.
– Open Group Base Specifications Issue 7, 2018 edition > set
foo () {...}
just looks so natural, you never think that the braces aren't part of the function syntax, rather than the mostly commonly used compound command. – Praedial