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

1

6

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
rc=$?
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 ...

output=$(command)

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

Underproof answered 7/9, 2016 at 1:35 Comment(0)
S
7

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

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

Documentation

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.

Statutable answered 7/9, 2016 at 1:38 Comment(1)
For some reason, rc wasn't being set properly when I tried this exact method. My test script must have had another error that I missed. Anyway, this is the answer I'm looking for. Thank you.Underproof

© 2022 - 2024 — McMap. All rights reserved.