For this question I will use grep
, because its usage text prints to stderr:
$ grep
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
You can capture stdout easily with process substitution:
$ read b < <(echo hello world)
However stderr slips past the process substitution and prints to the console:
$ read b < <(grep)
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
I would like to capture stderr using process substitution. I am using this now:
$ grep 2> log.txt
$ read b < log.txt
but I am hoping to avoid the temp file.
Redirect the stderr of your command to stdout:
$ read "b" < <(grep 2>&1)
$ echo "$b"
Usage: grep [OPTION]... PATTERN [FILE]...
Though the conventional way to save the output of a command to a variable in Bash is by using $()
:
$ b=$(grep 2>&1)
$ echo "$b"
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.