Bash: Backup and restore settings
From FVue
Contents
Problem
How do I backup and restore Bash settings?
Solution
There are different bash settings:
- 'set' options
- 'shopt' options
- traps
'set' options
First, you don't need to backup 'set' options if the script executes in a subshell. The changed settings vanish as soon as the subshell exits. For example:
$> cat foo.sh # The script #!/bin/bash set -o errexit set -o | grep errexit $> set -o | grep errexit errexit off # Setting is off in shell $> ./foo.sh # Execute script errexit on # Script turns setting on $> set -o | grep errexit errexit off # Setting is off again when subshell exits $>
You do need to backup 'set' options when the script is sourced (included) in the current shell. For example:
$> cat foo.sh # The script #!/bin/bash set -o errexit set -o | grep errexit $> set -o | grep errexit errexit off # Setting is off in shell $> . foo.sh # Source script errexit on # Script turns setting on $> set -o | grep errexit errexit on # Setting is on after script has finished $>
All
oldSetOptions=$(set +o) # Backup eval "$oldSetOptions" 2> /dev/null # Restore
Example output of set +o
:
set +o allexport set -o braceexpand set +o emacs set +o errexit set +o errtrace set +o functrace set -o hashall set -o histexpand set -o history set +o ignoreeof set -o interactive-comments set +o keyword set -o monitor set +o noclobber set +o noexec set +o noglob set +o nolog set +o notify set +o nounset set +o onecmd set +o physical set +o pipefail set +o posix set +o privileged set +o verbose set -o vi set +o xtrace
Single
Invoking a subshell ($() or ``) is relative heavy, so if you want to backup/restore a single `set' option, you can use this, e.g. for `set -f':
$ [[ $- = *f* ]]; oldf=$? # Save -f state $ set -f # Disable globbing $ (( $oldf )) && set +f # Reset -f if necessary
'shopt' options
Code to backup and restore 'shopt' options:
oldShoptOptions=$(shopt -p) # Backup eval "$oldShoptOptions" 2> /dev/null # Restore
Example output of shopt -p
:
shopt -u cdable_vars shopt -u cdspell shopt -u checkhash shopt -s checkwinsize shopt -s cmdhist shopt -u dotglob shopt -u execfail shopt -s expand_aliases shopt -u extdebug shopt -u extglob shopt -s extquote shopt -u failglob shopt -s force_fignore shopt -u gnu_errfmt shopt -u histreedit shopt -u histappend shopt -u histverify shopt -s hostcomplete shopt -u huponexit shopt -s interactive_comments shopt -u lithist shopt -u login_shell shopt -u mailwarn shopt -u no_empty_cmd_completion shopt -u nocaseglob shopt -u nullglob shopt -s progcomp shopt -s promptvars shopt -u restricted_shell shopt -u shift_verbose shopt -s sourcepath shopt -u xpg_echo
traps
Code to set and restore trap:
trap 'echo Error; exit' ERR # Set ERR trap trap - SIGNAL # Restore ERR trap
Advertisement