Suppose I'm using a shell like bash or zsh, and also suppose that I have a command which writes to stdout. I want to capture the output of the command into a shell variable, and also to capture the command's return code into another shell variable.
I know I can do something like this ...
$? as you did before. Using the executables
false, we can demonstrate that command substitution does set a proper return code:
$ output=$(true); rc=$?; echo $rc 0 $ output=$(false); rc=$?; echo $rc 1
If more than one command substitution appears in an assignment, the return code of the last command substitution determines the return code of the assignment:
$ output="$(true) $(false)"; rc=$?; echo $rc 1 $ output="$(false) $(true)"; rc=$?; echo $rc 0
From the section of
man bash describing variable assignment:
If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero.