Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process substitution capture stderr

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.

like image 874
Zombo Avatar asked Mar 13 '13 17:03

Zombo


People also ask

How does process substitution work?

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.

How would you redirect a command stderr to stdout?

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.


1 Answers

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.
like image 108
Christopher Neylan Avatar answered Oct 02 '22 19:10

Christopher Neylan