在单个命令中将一个命令的输出附加到另一个命令的输出

dhe*_*aur 2 unix bash stdout pipe

有没有办法将一个命令的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
Run Code Online (Sandbox Code Playgroud)

有没有办法在一个命令中执行此操作?

Jam*_*ley 5

只需将两个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.
Run Code Online (Sandbox Code Playgroud)

所以:

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
Run Code Online (Sandbox Code Playgroud)

你可以使用花括号来达到类似的效果,但花括号有一些语法差异(例如,它们在括号和其他单词之间需要空格时更加挑剔).最大的区别是大括号内的命令在当前的 shell环境中运行,因此它们会影响您的环境.例如:

james@bodacious-wired:tmp$HELLO=world; (HELLO=MyFriend); echo $HELLO
world
james@bodacious-wired:tmp$HELLO=world; { HELLO=MyFriend; }; echo $HELLO
MyFriend
Run Code Online (Sandbox Code Playgroud)

如果你想真正想要你可以定义一个函数并执行它:

james@bodacious-wired:tmp$myfunc () (
> cat one.txt
> cat two.txt
> )
james@bodacious-wired:tmp$myfunc | xargs echo
one two
james@bodacious-wired:tmp$
Run Code Online (Sandbox Code Playgroud)