HippoMan HippoMan - 1 year ago 121
Bash Question

shell: capture command output and return status in two different variables

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 ...

command >tempfile
output=$(cat tempfile)

Then, I have the return code in the 'rc' shell variable and the command's output in the 'output' shell variable.

However, I want to do this without using any temporary files.

Also, I could do this to get the command output ...


... but then, I don't know how to get the command's return code into any shell variable.

Can anyone suggest a way to get both the return code and the command's output into two shell variables without using any files?

Thank you very much.

Answer Source

Just capture $? as you did before. Using the executables true and false, we can demonstrate that command substitution does set a proper return code:

$ output=$(true); rc=$?; echo $rc
$ output=$(false); rc=$?; echo $rc

Multiple command substitutions in one assignment

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
$ output="$(false) $(true)"; rc=$?; echo $rc


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download