将多个命令重定向为输入

und*_*kor 4 io-redirection input

将多个命令的输出重定向为另一个命令的输入的正确方法是什么?

例如

$ command < (command2 | grep pattern)
Run Code Online (Sandbox Code Playgroud)

Hau*_*ing 5

(如有疑问,这是指bash)

通过创建(或扩展现有)管道,可以将一个命令或一个管道的输出作为另一个命令的输入:

command1 | command2
command1 | command2 | command3
Run Code Online (Sandbox Code Playgroud)

多个命令(包括管道)可以与子外壳或列表(组命令)组合。这个组合成为管道的第一部分,然后:

(command1; command2 | command3; command4) | command5
{command1; command2 | command3; command4;} | command5 # note the ; before }
Run Code Online (Sandbox Code Playgroud)

另一种可能性是“here string”(甚至“here文档”):

command2 <<< $(command1)

command2 <<EOT
First input line
$(command1)
Last input line
EOT
Run Code Online (Sandbox Code Playgroud)

其他情况

当输出应是命令行的一部分时使用命令替换,即如果一个命令应将另一个命令的输出视为其自己的参数:

echo $(date)
Run Code Online (Sandbox Code Playgroud)

echo 将 的输出date视为其参数;就好像它是在命令行中输入的一样。

进程替换使另一个进程的输出显示为在命令行上作为参数给出的(不可查找的)文件的内容。

grep bar <(echo $'foo\nbar\nbaz')
Run Code Online (Sandbox Code Playgroud)

看起来像 grep

echo $'foo\nbar\nbaz' > /path/to/file
grep bar /path/to/file
Run Code Online (Sandbox Code Playgroud)