bash 将多个命令管道化为一个命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11917708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pipe multiple commands into a single command
提问by Rob Bednark
How can I pipe the stdout of multiple commands to a single command?
如何将多个命令的标准输出通过管道传输到单个命令?
Example 1: combine and sort the output of all three echo commands:
示例 1:对所有三个 echo 命令的输出进行组合和排序:
echo zzz; echo aaa; echo kkk
desired output:
所需的输出:
aaa
kkk
zzz
Example 2: rewrite the following so that all the commands are in a single command-line using pipes, without redirects to a temp file:
示例 2:重写以下内容,以便所有命令都在使用管道的单个命令行中,而不重定向到临时文件:
setopt > /tmp/foo; unsetopt >> /tmp/foo; set >> /tmp/foo; sort /tmp/foo
回答by Rob Bednark
Use parentheses ()'s to combine the commands into a single process, which will concatenate the stdout of each of them.
使用括号 () 将命令组合成一个进程,这将连接每个命令的标准输出。
Example 1 (note that $
is the shell prompt):
示例 1(注意$
是 shell 提示):
$ (echo zzz; echo aaa; echo kkk) | sort
aaa
kkk
zzz
Example 2:
示例 2:
(setopt; unsetopt; set) | sort
回答by codeforester
You can use {}
for this and eliminate the need for a sub-shell as in (list)
, like so:
您可以使用{}
它并消除对子 shell 的需要(list)
,如下所示:
{ echo zzz; echo aaa; echo kkk; } | sort
We do need a whitespace character after {
and before }
. We also need the last ;
when the sequence is written on a single line.
我们确实需要在 之后{
和之前有一个空格字符}
。;
当序列写在一行上时,我们还需要最后一个。
We could also write it on multiple lines without the need for any ;
:
我们也可以将它写在多行上,而无需任何;
:
Example 1:
示例 1:
{
echo zzz
echo aaa
echo kkk
} | sort
Example 2:
示例 2:
{
setopt
unsetopt
set
} | sort
回答by Claudio
In Windows it would be as follow: (echo zzz & echo aaa & echo kkk) | sort
在 Windows 中,它将如下所示: (echo zzz & echo aaa & echo kkk) | sort
Or if it is inside a batch file it can be mono line (like sample) as well as multiline:
或者如果它在批处理文件中,它可以是单行(如样本)以及多行:
(
echo zzz
echo aaa
echo kkk
) | sort
Note: The original post does not mention it is only for Linux, so I added the solution for Windows command line... it is very useful when working with VHD/VHDX with diskpart inside scripts (echo diskpart_command
) instead of the echo on the same, but let there the echo
, there is also another way without echos and with >
redirector, but it is very prone to errors and much more complex to write (why use a complicated prone to errors way if exists a simple way that allways work well)... also remember %d%
gives you the actual path (very useful for not hardcoding the path of VHD/VHDX files).
注意:原帖没有提到它仅适用于 Linux,所以我添加了 Windows 命令行的解决方案......当使用 VHD/VHDX 与脚本中的 diskpart(echo diskpart_command
)而不是相同的 echo时,它非常有用,但是echo
,还有另一种没有回声和>
重定向器的方法,但它很容易出错,而且编写起来要复杂得多(如果存在一种始终运行良好的简单方法,为什么要使用复杂的容易出错的方法)。 . 还记得%d%
为您提供实际路径(对于不硬编码 VHD/VHDX 文件的路径非常有用)。