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

标签 bash io-redirection

我有一个包含以下两个命令的 bash 脚本:

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

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

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

最佳答案

要么在 >>> 中使用 '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 功能作为super-grep 将其合二为一 — 我只解决了如何将两个命令的 I/O 重定向到一个文件的表面问题。

关于bash - 如何将多个命令的输出重定向到一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20355264/

相关文章:

linux - 将正在运行的程序的输出重定向到可以分析的文件中

linux - 将输入从一个 shell 传递到另一个 shell,然后再次返回输入

linux - 用于配置网络接口(interface)的 Bash 脚本

php - 一直运行的进程

Bash: "printf %q $str"在脚本中删除空格。 (备择方案?)

c++ - 为什么在重定向 stdout 和 stdin 时 Python 的行为不符合预期?

java - 输入重定向到键盘输入

perl - 将 STDERR 重定向到 select()ed STDOUT

c++ - 如何从 std::cin 读取直到流结束?

linux - 为什么这段代码在 bash 中不起作用?