use*_*207 20 bash io-redirection
我有一个bash脚本,它有以下两个命令:
ssh host tail -f /some/file | awk ..... > /some/file &
ssh host tail -f /some/file | grep .... > /some/file &
Run Code Online (Sandbox Code Playgroud)
如何将两个命令的输出定向到同一个文件中.
Jon*_*ler 30
使用'append' >>或使用大括号来包含I/O重定向,或(偶尔)使用exec:
ssh host tail -f /some/file | awk ..... > /some/file &
ssh host tail -f /some/file | grep .... >> /some/file &
Run Code Online (Sandbox Code Playgroud)
要么:
{
ssh host tail -f /some/file | awk ..... &
ssh host tail -f /some/file | grep .... &
} > /some/file
Run Code Online (Sandbox Code Playgroud)
要么:
exec > /some/file
ssh host tail -f /some/file | awk ..... &
ssh host tail -f /some/file | grep .... &
Run Code Online (Sandbox Code Playgroud)
之后exec,脚本的标准输出作为一个整体/some/file.我很少使用这种技术; 我经常使用这种{ ...; }技术.
注意:您必须小心括号表示法.我展示的内容将起作用.试图将其展平为一行需要您将其{视为命令(例如,后跟空格),并将其}视为命令.你必须有一个命令终止符}- 我使用了换行符,但是&用于后台或者;也可以用.
从而:
{ command1; command2; } >/some/file
{ command1 & command2 & } >/some/file
Run Code Online (Sandbox Code Playgroud)
我还没有解决为什么你有两个独立的tail -f操作在一个远程文件上运行的问题,以及为什么你没有使用awk电源作为超级grep处理器来处理它 - 我只解决了如何重定向的表面问题两个命令的I/O到一个文件.
gle*_*man 17
请注意,您可以减少ssh调用的次数:
{ ssh host tail -f /some/file |
tee >(awk ...) >(grep ...) >/dev/null
} > /some/file &
Run Code Online (Sandbox Code Playgroud)
例:
{ echo foobar | tee >(sed 's/foo/FOO/') >(sed 's/bar/BAR/') > /dev/null; } > outputfile
cat outputfile
Run Code Online (Sandbox Code Playgroud)
fooBAR
FOObar
Run Code Online (Sandbox Code Playgroud)