title: Using set -e / set +e in bash with functions
body: <p>I've been using a simple bash preamble like this in my scripts: </p>
  
  <pre><code>#!/bin/bash
  set -e
  </code></pre>
  
  <p>In conjunction with modularity / using functions this has bitten me today. </p>
  
  <p>So, say I have a function somewhere like</p>
  
  <pre><code>foo() {
    #edit: some error happens that make me want to exit the function and signal that to the caller 
    return 2
  }
  </code></pre>
  
  <p>Ideally I'd like to be able to use multiple small files, include their functions in other files and then call these functions like</p>
  
  <pre><code>set +e
  foo
  rc=$?
  set -e
  </code></pre>
  
  <p>. This works for exactly two layers of routines. But if foo is also calling subroutines like that, the last setting before the return will be <code>set -e</code>, which will make the script exit on the return - I cannot override this in the calling function. So, what I had to do is</p>
  
  <pre><code>foo() {
    #calling bar() in a shielded way like above
    #..      
  
    set +e
    return 2
  }
  </code></pre>
  
  <p>Which I find very counterintuitive (and also not what I want - what if in some contexts I'd like to use the function without shielding against failures, while in other contexts I want to handle the cleanup?) What's the best way to handle this? Btw. I'm doing this on OSX, I haven't tested whether this behaviour is different on Linux.</p>