title: Bash return code error handling when using heredoc input
body: <p><strong>Motivation</strong></p>
  
  <p>I'm in a situation where I have to run multiple bash commands with a single bash invocation without the possibility to write a full script file (use case: <a href="https://stackoverflow.com/q/33979501/1804173">Passing multiple commands to a container in Kubernetes</a>). A <a href="https://stackoverflow.com/a/49801587/1804173">common solution</a> is to combine commands with <code>;</code> or <code>&amp;&amp;</code>, for instance:</p>
  
  <pre class="lang-sh prettyprint-override"><code>bash -c " \
  echo \"Hello World\" ; \
  ls -la ; \
  run_some_command "
  </code></pre>
  
  <p>In practice writing bash scripts like that turns out to be error prone, because I often forget the semicolon leading to subtle bugs.</p>
  
  <p>Inspired by <a href="https://stackoverflow.com/q/27012174/1804173">this question</a>, I was experiment with writing scripts in a more standard style by using a heredoc:</p>
  
  <pre class="lang-sh prettyprint-override"><code>bash &lt;&lt;EOF
  echo "Hello World"
  ls -la
  run_some_command
  EOF
  </code></pre>
  
  <hr>
  
  <p>Unfortunately, I noticed that there is a difference in exit code error handling when using a heredoc. For instance:</p>
  
  <pre class="lang-sh prettyprint-override"><code>bash -c " \
  run_non_existing_command ; \
  echo $? "
  </code></pre>
  
  <p>outputs (note that <code>$?</code> properly captures the exit code):</p>
  
  <pre><code>bash: run_non_existing_command: command not found
  127
  </code></pre>
  
  <p>whereas</p>
  
  <pre class="lang-sh prettyprint-override"><code>bash &lt;&lt;EOF
  run_non_existing_command
  echo $?
  EOF
  </code></pre>
  
  <p>outputs (note that <code>$?</code> fails to capture the exit code compared to standard script execution):</p>
  
  <pre><code>bash: line 1: run_non_existing_command: command not found
  0
  </code></pre>
  
  <p>Why is the heredoc version behaving differently? Is it possible to write the script in the heredoc style and maintaining normal exit code handling?</p>