Bash, &&-ed 命令列表输出重定向到标准输出

Bash, &&-ed command list output redirect to stdout

我的主要 Bash 知识来源是 info Bash。它的 RedirectionsCommands > Lists 部分都没有详细说明命令列表如何处理重定向命令输出。如果这里是 &&-ed 命令列表:command1 && command2 && command3。 需要的是将所有 3 个命令的输出重定向到文件。 对于此处使用的 Bash,以下两种方法均无效(在文件重定向中只能找到 command3 输出)

command1 && command2 && command3 > mycommandoutput.txt

(command1 && command2 && command3) > mycommandoutput.txt

command1 > mycommandoutput.txt && command2 > mycommandoutput.txt && command3 > mycommandoutput.txt

command1 | tee mycommandoutput.txt && command2 | tee mycommandoutput.txt && command3 | tee mycommandoutput.txt

command1 && command2 && command3 | tee mycommandoutput.txt

也尝试了一些,没有帮助。

这个Bash方面在哪里指定的?

为什么我的命令字符串没有产生描述的结果?

如何解决?

重定向多个命令的常用方法是使用一个组 { ...; }。注意最后的;,很重要。

{ cmd1 && cmd2 && cmd3; } > file

但是,您说您已经尝试过 (cmd1 && cmd1 && cmd3) > file,这应该也有效。也许您的某些命令会打印到 stderr 而不是 stdout。在这种情况下,使用 { ...; } &> file 将 stderr 和 stdout 写入文件。

为什么其他命令不起作用?

除了 stdout/stderr 问题之外,以下解释了为什么其他命令对您不起作用:

  • cmd1 && cmd2 && cmd3 > file 仅重定向 cmd3.
  • cmd1 > file && cmd2 > file && cmd3 > file 覆盖 file 两次。 cmd1 的输出丢失了,因为 cmd2 覆盖了它。 cmd2 的输出丢失了,因为 cmd3 覆盖了它。使用 cmd1 > file && cmd2 >> file && cmd3 >> file.
  • 附加到文件,而不是覆盖
  • cmd1 | tee file && cmd2 | tee file && cmd3 | tee file同上; tee 覆盖文件。使用 tee -a 来追加。