进程替换捕获stderr

6 bash stderr process-substitution

我将使用这个问题grep,因为它的用法文本打印到stderr

$ grep
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
Run Code Online (Sandbox Code Playgroud)

您可以使用流程替换轻松捕获stdout

$ read b < <(echo hello world)
Run Code Online (Sandbox Code Playgroud)

然而,stderr滑过进程替换并打印到控制台

$ read b < <(grep)
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
Run Code Online (Sandbox Code Playgroud)

我想使用进程替换来捕获stderr.我现在正在使用它

$ grep 2> log.txt

$ read b < log.txt
Run Code Online (Sandbox Code Playgroud)

但我希望避免临时文件.

Chr*_*lan 8

将命令的stderr重定向到stdout:

$ read "b" < <(grep 2>&1)
$ echo "$b"
Usage: grep [OPTION]... PATTERN [FILE]...
Run Code Online (Sandbox Code Playgroud)

虽然在Bash中将命令输出保存到变量的传统方法是使用$():

$ b=$(grep 2>&1)
$ echo "$b"
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.
Run Code Online (Sandbox Code Playgroud)