Sunday, September 4, 2016

Saving and restoring bash "shopt" options

Saving and restoring bash "shopt" options

The following command prints out a series of shopt commands to restore your current options.

shopt -p 

as a a series of shopt commands like so

shopt -s xxx
shopt -u yyy
shopt -u zzz

commands.  One minor problem is these commands are newline separated.   

opts=$(shopt -p)
echo $opts     # BAD ack newlines get converted to spaces
echo "$opts"   # GOOD double quotes keep the newlines.

In trying to use $opts, bash does word splitting and turns the newlines into spaces because consecutive newlines, spaces and tabs are converted into a single space.  However enclosing $opts in double quotes preserves the newlines.

someBashFn() {
  local prevOpts=$(shopt -p)

  ... your code which uses shopt ...

  eval "$prevOpts"   # restore the options
}