Flag for Exiting on Errors (set -e)

TLDR: set -e is not full proof and comes with caveats.

Arguments against set -e

Example

✅ Basic example works well
set -e

foo() {
  echo "This is foo; returns 1 (unhappy)"
  return 1
}

main() {
  foo

  echo.green "MAIN FINISHED! (after foo calls)"
}

main "${@}"
m:mac d:kotlin-mp b:master ○❯sr
This is foo; returns 1 (unhappy)
m:mac d:kotlin-mp b:master ○❯
❌ Checking for success of funcion prevents 'set -e' trigger on failure.
set -e

foo() {
  echo "This is foo; returns 1 (unhappy)"
  return 1
}

main() {
  foo && echo "Foo succeeded!"

  echo.green "MAIN FINISHED! (after foo calls)"
}

main "${@}"
m:mac d:kotlin-mp b:master ○❯sr
This is foo; returns 1 (unhappy)
MAIN FINISHED! (after foo calls)
m:mac d:kotlin-mp b:master ○❯
❌ 'local' used on the same line will prevent 'set -e' from aborting

set -e

foo() {
  echo "This is foo; returns 1 (unhappy)"
  return 1
}

main() {
  echo "Calling foo()"
  # We succeed because of 'local' being used on the same line as the function call.
  local foo_capture="$(foo)"
  echo "After foo()"

  echo.green "MAIN FINISHED! (after foo calls), foo_capture=[${foo_capture}]"
}

main "${@}"

Output:

m:mac d:kotlin-mp b:master ○❯sr
Calling foo()
After foo()
MAIN FINISHED! (after foo calls), foo_capture=[This is foo; returns 1 (unhappy)]
m:mac d:kotlin-mp b:master ○❯

IF we were to split up declaration of foo_capture into

local foo_capture
foo_capture="$(foo)"

Then set -e would trigger and script would stop.


Children
  1. ❌ 'local' used on the same line with function call will prevent 'set -e' from aborting script