title: How do I get the effect and usefulness of "set -e" inside a shell function?
body: <p><code>set -e</code> (or a script starting with <code>#!/bin/sh -e</code>) is extremely useful to automatically bomb out if there is a problem. It saves me having to error check every single command that might fail.</p>
  
  <p>How do I get the equivalent of this inside a function?</p>
  
  <p>For example, I have the following script that exits immediately on error with an error exit status:</p>
  
  <pre><code>#!/bin/sh -e
  
  echo "the following command could fail:"
  false
  echo "this is after the command that fails"
  </code></pre>
  
  <p>The output is as expected:</p>
  
  <pre><code>the following command could fail:
  </code></pre>
  
  <p>Now I'd like to wrap this into a function:</p>
  
  <pre><code>#!/bin/sh -e
  
  my_function() {
      echo "the following command could fail:"
      false
      echo "this is after the command that fails"
  }
  
  if ! my_function; then
      echo "dealing with the problem"
  fi
  
  echo "run this all the time regardless of the success of my_function"
  </code></pre>
  
  <p>Expected output:</p>
  
  <pre><code>the following command could fail:
  dealing with the problem
  run this all the time regardless of the success of my_function
  </code></pre>
  
  <p>Actual output:</p>
  
  <pre><code>the following output could fail:
  this is after the command that fails
  run this all the time regardless of the success of my_function
  </code></pre>
  
  <p>(ie. the function is ignoring <code>set -e</code>)</p>
  
  <p>This presumably is expected behaviour. My question is: how do I get the effect and usefulness of <code>set -e</code> inside a shell function? I'd like to be able to set something up such that I don't have to individually error check every call, but the script will stop on encountering an error. It should unwind the stack as far as is needed until I do check the result, or exit the script itself if I haven't checked it. This is what <code>set -e</code> does already, except it doesn't nest.</p>
  
  <p>I've found <a href="http://www.unix.com/shell-programming-scripting/114716-strange-behaviour-set-e-functions.html" rel="noreferrer">the same question</a> asked outside Stack Overflow but no suitable answer.</p>