title: How to check the error code of a command executed by "bash -c ''"?
body: <p>I had some invocation of RSYNC like in the following example. For various reasons the error code of RSYNC is required as well and retrieved using <code>$?</code> after the statement. AFAIK even though two commands are executed in this example, the error code should really be that of RSYNC instead of NICE. Though, I don't know if NICE forwards that code of RSYNC by design or replaces itself with RSYNC, so that only that code gets generated. Doesn't matter too much anyway, the received codes properly map to how RSYNC behaves.</p>
  <pre><code>/[...]/nice [...] /[...]/rsync [...]
  </code></pre>
  <p>That statement above needed to be changed to log output of RSYNC as well. From my understanding this is pretty mich like with other cases of SUDO etc., where adding shell redirection at the same level doesn't work. Instead of RSYNC, the shell redirection would cover the output of NICE in, maybe depending on how NICE actually works internally. Anyway, starting a new shall with its own specific redirection should be safe always, like in the following example:</p>
  <pre><code>/[...]/nice [...] bash -c &quot;/[...]/rsync [...] &gt; [...] 2&gt;&amp;1&quot;
  </code></pre>
  <p><strong>And here's the point: Which error code does <code>$?</code> right after that statement retrieve now?</strong></p>
  <p>Is BASH returning the error code of the last executed command or does it always return <code>0</code>, as its own execution succeeded? If it forwards the error code of RSYNC, everything would be fine like with not using intermediate BASH in the past. OTOH, it might be necessary to additionally trigger BASH to exit in case of errors, possibly forwarding the last error code this way:</p>
  <pre><code>/[...]/nice [...] bash -c &quot;set -o errexit ; /[...]/rsync [...] &gt; [...] 2&gt;&amp;1&quot;
  </code></pre>
  <p>I've tested the second and third example on the shell with <code>rsync --version</code> vs. <code>rsync --version_</code>, with the latter leading to an error message of RSYNC as intended. In both cases it seems that BASH properly returns the error code of RSYNC itself. Though, I couldn't find too much documentation about that behaviour, example what happens in case of multiple commands executed using <code>-c</code> etc.</p>
  <p><strong>So, how to properly check the error code of a command executed using <code>bash -c '[...]'</code>? Is e.g. <code>set -o errexit</code> necessary at all, might it even harm?</strong></p>
  <p>Thanks!</p>