title: How to safely exit early from a bash script?
body: <p>I know there are several SO questions on <code>exit</code> vs. <code>return</code> in <code>bash</code> scripts (e.g. <a href="https://stackoverflow.com/questions/4419952/difference-between-return-and-exit-in-bash-functions">here</a>).</p>
  
  <p>On this topic, but different from existing questions, I believe, I'd like to know if there is a "best practice" for how to safely implement "early return" from a <code>bash</code> script such that the user's current shell is not exited if they source the script.</p>
  
  <p>Answers such as <a href="https://stackoverflow.com/questions/1378274/in-a-bash-script-how-can-i-exit-the-entire-script-if-a-certain-condition-occurs">this</a> seem based on "<code>exit</code>", but if the script is sourced, i.e. run with a "<code>.</code>" (dot space) prefix, the script runs in the <em>current shell</em>'s context, in which case <code>exit</code> statements have the effect of exiting the current shell. I assume this is an undesirable result because a script doesn't know if it is being sourced or being run in a subshell - if the former, the user may unexpectedly have his shell disappear. Is there a way/best practice for early-returns to not exit the current shell if the caller sources it?</p>
  
  <p>E.g. This script...</p>
  
  <pre><code>#! /usr/bin/bash
  # f.sh
  
  func()
  {
    return 42
  }
  
  func
  retVal=$?
  if [ "${retVal}" -ne 0 ]; then
    exit "${retVal}"
  #  return ${retVal} # Can't do this; I get a "./f.sh: line 13: return: can only `return' from a function or sourced script"
  fi
  
  echo "don't wanna reach here"
  </code></pre>
  
  <p>...runs without killing my current shell if it is run from a subshell...</p>
  
  <pre><code>&gt; ./f.sh 
  &gt; 
  </code></pre>
  
  <p>...but kills my current shell if it is sourced:</p>
  
  <pre><code>&gt; . ./f.sh 
  </code></pre>
  
  <p>One idea that comes to mind is to nest code within coditionals so that there is no explicit <code>exit</code> statement, but my <code>C</code>/<code>C++</code> bias makes think of early-returns as aesthetically preferable to nested code. Are there other solutions that are truly "early return"?</p>