1

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?

leetbacoon
  • 1,111
  • 2
  • 9
  • 32
  • Possible duplicate of https://stackoverflow.com/questions/13806626/capture-both-stdout-and-stderr-in-bash and https://stackoverflow.com/questions/11027679/capture-stdout-and-stderr-into-different-variables – John1024 Sep 02 '20 at 22:26

1 Answers1

4

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.$$
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks, this looks like it works. Is there a way to do with without having to write files? – leetbacoon Sep 02 '20 at 22:08
  • Can't think of any. You can only assign to one variable at a time. – Barmar Sep 02 '20 at 22:08
  • 1
    If I knew a better way, don't you think I would have put that in the answer instead? – Barmar Sep 02 '20 at 22:10
  • For symmetry, you could redirect *both* streams to files, then read them both into their respective variables :) – chepner Sep 02 '20 at 22:10
  • Is something like this possible? I can't get it to work, but I'm probably missing something: `command_stderr="$(command_stdout="$(mycommand --flag)" 2>&1)"` – leetbacoon Sep 02 '20 at 22:12
  • 1
    No, because the `command_stdout` assignment is happening in a subshell, it won't be visible in the main shell. – Barmar Sep 02 '20 at 22:16