Is it possible to check whether -e is set within a bash script?

9

1

If a shell function needs a specific setting of -e/+e in order to work, is it possible to set that setting locally and then restore it to its previous setting before exiting the function?

myfunction()
{
   # Query here if -e is set and remember in a variable?
   # Or push the settings to then pop at the end of the function?
   set +e
   dosomething
   doanotherthing
   # Restore -e/+e as appropriate, don't just do unconditional   set -e
}

usta

Posted 2015-11-08T15:26:56.190

Reputation: 237

Answers

12

You have the flags currently set in the variable $-, so you can preserve this at the start of function and restore it after.

save=$-
...
if [[ $save =~ e ]]
then set -e
else set +e
fi

meuh

Posted 2015-11-08T15:26:56.190

Reputation: 4 273

It should be noted that $- also works in /bin/sh and you probably don't need bashisms to parse it, just use e.g. globbing that case provides – Josip Rodin – 2017-07-06T10:50:45.077

2

You can read the flag value thru the variable SHELLOPTS:

  > set +e 
  > echo $SHELLOPTS
    braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
  > set -e 
  > echo $SHELLOPTS
    braceexpand:emacs:errexit:hashall:histexpand:history:interactive-comments:monitor

You see that, after setting set -e, the value errexit in $SHELLOPTS appears. You can check it from there.

However, you can get around this (if you wish!) by remembering the following point: according to the Manual:

-e:

..... This option applies to the shell environment and each subshell environment separately.

Thus, if you execute your function in a subshell, like

   zz="$(myfunction)"

you do not have to worry whether the errexit variable is set or not in calling environment, and you may set it as you like.

MariusMatutiae

Posted 2015-11-08T15:26:56.190

Reputation: 41 321

Thanks, SHELLOPTS is useful to be aware of. I do find $- suggested by @meuh easier to check programmatically though, that's why I accepted that answer. – usta – 2015-11-09T17:45:26.993

The note about subshells is useful too, but I wanted to avoid modifying the call sites. Otherwise I would probably change myfunction calls to myfunction || true to suppress the effect of -e for the calls and not have to do set +e inside the function in the first place. – usta – 2015-11-09T17:51:31.633

@MariusMatutiae: 20000 congratulations. – Scott – 2015-11-10T09:25:05.293