如何将多个命令的输出重定向到一个文件

时间:2013-12-03 15:34:25

标签: bash io-redirection

我有一个bash脚本,它有以下两个命令:

ssh host tail -f /some/file | awk ..... > /some/file &

ssh host tail -f /some/file | grep .... > /some/file &

如何将两个命令的输出定向到同一个文件中。

3 个答案:

答案 0 :(得分:29)

使用{append'与>>或使用大括号来包含I / O重定向,或(偶尔)使用exec

ssh host tail -f /some/file | awk ..... >  /some/file &
ssh host tail -f /some/file | grep .... >> /some/file &

或:

{
ssh host tail -f /some/file | awk ..... &
ssh host tail -f /some/file | grep .... &
} > /some/file

或:

exec > /some/file
ssh host tail -f /some/file | awk ..... &
ssh host tail -f /some/file | grep .... &

exec之后,脚本的标准输出作为一个整体转到/some/file。我很少使用这种技术;我通常使用{ ...; }技术。

注意:您必须小心使用括号表示法。我展示的内容将起作用。尝试将其展平为一行需要您将{视为命令(例如,后跟空格),并将}视为命令。你必须在}之前有一个命令终止符 - 我使用换行符,但&作为背景或;也可以使用。

因此:

{ command1;  command2;  } >/some/file
{ command1 & command2 & } >/some/file

我还没有解决为什么你在一个远程文件上运行两个单独的tail -f操作以及为什么你没有使用awk权力作为超级grep来解决这个问题的问题。处理所有这一切 - 我只解决了如何将两个命令的I / O重定向到一个文件的表面问题。

答案 1 :(得分:17)

请注意,您可以减少ssh调用次数:

{  ssh host tail -f /some/file | 
     tee >(awk ...) >(grep ...) >/dev/null
} > /some/file &

示例:

{ echo foobar | tee >(sed 's/foo/FOO/') >(sed 's/bar/BAR/') > /dev/null; } > outputfile
cat outputfile 
fooBAR
FOObar

答案 2 :(得分:2)

对此的最佳答案是可能摆脱ssh .... | grep ...行,并修改另一个命令中的awk脚本以添加从grep命令获得的功能...

这将消除任何交错问题作为奖励副作用。

相关问题