Here's example that tries to execute command and checks if it was executed successfully, while capturing it's output for further processing:
#!/bin/bash
readonly OUTPUT=$(foo)
readonly RES=$?
if [[ ${RES} != 0 ]]
then
echo "failed to execute foo"
exit 1
else
echo "foo success: '${OUTPUT}'"
fi
It reports that it was a success, even there is no such foo
executable. But, if I remove readonly
from OUTPUT
variable, it preserves erroneous exit code and failure is detected.
I try to use readonly as for "defensive programming" technique as recommended somewhere... but looks like it bites itself in this case.
Is there some clean solution to preserve readonly
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 readonly
ever...
Using Bash 4.2.37(1) on Debian Wheezy.