Why using Bash readonly variable to capture output fails to capture return code $? : <p>Here's example that tries to execute command and checks if it was executed successfully, while capturing it's output for further processing:</p>

<pre><code>#!/bin/bash

readonly OUTPUT=$(foo)
readonly RES=$?

if [[ ${RES} != 0 ]]
then
    echo "failed to execute foo"
    exit 1
else
    echo "foo success: '${OUTPUT}'"
fi
</code></pre>

<p>It reports that it was a success, even there is no such <code>foo</code> executable. But, if I remove <code>readonly</code> from <code>OUTPUT</code> variable, it preserves erroneous exit code and failure is detected.</p>

<p>I try to use readonly as for "defensive programming" technique as recommended somewhere... but looks like it bites itself in this case.</p>

<p>Is there some clean solution to preserve <code>readonly</code> while still capturing exit code of command/subshell? It would be disappointing that one has to remember this kind of exceptional use case, or revert to not using <code>readonly</code> ever...</p>

<p>Using Bash 4.2.37(1) on Debian Wheezy.</p>
