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.
In computing, process substitution is a form of inter-process communication that allows the input or output of a command to appear as a file. The command is substituted in-line, where a file name would normally occur, by the command shell.
Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With