有没有办法将一个命令的 stdout 输出附加到另一个命令,并将合并的输出通过管道传输到另一个命令?我曾经使用以下方法(以ack-grep
为例)
# List all python, js files in different directories
ack-grep -f --py apps/ > temp
ack-grep -f --js -f media/js >> temp
cat temp | xargs somecommand
有没有一种方法可以在一条命令中做到这一点?
最佳答案
只需将两个 ack-grep
命令作为复合命令运行即可;然后管道 compund 命令的结果。 man bash
中定义的第一个复合命令是括号:
(list) list is executed in a subshell environment (see COMMAND EXECU-
TION ENVIRONMENT below). Variable assignments and builtin com-
mands that affect the shell's environment do not remain in
effect after the command completes. The return status is the
exit status of list.
所以:
james@bodacious-wired:tmp$echo one > one.txt
james@bodacious-wired:tmp$echo two > two.txt
james@bodacious-wired:tmp$(cat one.txt; cat two.txt) | xargs echo
one two
您可以使用花括号来达到类似的效果,但是花括号在语法上有一些差异(例如,它们对花括号和其他单词之间需要空格更加挑剔)。最大的区别是大括号内的命令在当前 shell 环境中运行,因此它们会影响您的环境。例如:
james@bodacious-wired:tmp$HELLO=world; (HELLO=MyFriend); echo $HELLO
world
james@bodacious-wired:tmp$HELLO=world; { HELLO=MyFriend; }; echo $HELLO
MyFriend
如果你真的很喜欢,你可以定义一个函数并执行它:
james@bodacious-wired:tmp$myfunc () (
> cat one.txt
> cat two.txt
> )
james@bodacious-wired:tmp$myfunc | xargs echo
one two
james@bodacious-wired:tmp$
关于bash - 在单个命令中将一个命令的输出附加到另一个命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9108181/