In my script, I have a complicated command that generates output both on stdout and stderr. I need to capture both into separate variables:
#!/bin/sh
A=$(command)
How can I "capture" stderr into a variable B ?
I have tried some variations with 2>&1 and read but that does not work:
A=$(some_command) 2>&1 | read B
echo $B
or
{ OUT="$(command)" 2>&1 | read B ; }
echo $B
The only way that works is to redirect stderr into a temporary file, and then read it back. But that seems like a dirty hack. Is there a way to do it without using temporary files?
UPDATE
to clarify, both stdout and stderr will be multi-line outputs.
read Bcommand imply that you only expect to read a single line from the standard error stream? – Kusalananda Sep 12 '22 at 09:22