Bash – `set -e` inside a bash function

bashbash-functionsshell-script

Does set -e behave differently here

set -e;

function foo {

}

vs.

function foo {
  set -e;

}

does set -e belong inside functions? Does set -e declared outside of functions, affect "nested" functions inside a shell file? What about the inverse? Should we call local set -e lol?

Best Answer

Note: the statements here apply to Bash version 4.0.35 and up. Implementations of set -e vary wildly among different shells/versions. Follow Stéphane's advice and don't use set -e.

man bash in the Shell Builtin Commands/set section explains things pretty well though the text is a little dense and requires a bit of focus. To your specific questions the answers are:

  • Does set -e behave different here...vs.. - Depends on what you mean by "differently" but I suspect you'd consider the answer "no"...there are no tricky scoping rules. It acts quite linearlly.
  • Does set -e belong inside functions? - Perfectly valid.
  • Does set -e declared outside of functions, affect "nested" functions inside a shell file? - Yes
  • What about the inverse? - set -e in a function and then encounter a non-zero status after return? Yes, this will exit.
Related Question