bash: Run a command once and save stdout and stderr in their own variables

80 Views Asked by At

I need to ensure a command is outputting the correct text. I currently have:

command_stdout="$(mycommand --flag 2>/dev/null)"
command_stderr="$(mycommand --flag 2>&1 1>/dev/null)"

Instead of having to run the same command twice, is there any way I can run it once but still be able to save stdout and stderr's output to their appropriate variables?

1

There are 1 best solutions below

6
On

Redirect stderr to a file, then set the second variable to the file contents.

command_stdout="$(mycommand --flag 2>/tmp/stderr.$$)"
command_stderr="$(</tmp/stderr.$$)"
rm /tmp/stderr.$$