如何将stderr和stdout重定向到多个输出文件?

时间:2014-08-08 01:46:02

标签: linux shell redirect

我想知道如何编写3个命令:

  • 将输出从stdout重定向到文件output.txt
  • 将输出从stderr重定向到文件error.txt
  • 将stdout和stderr的输出重定向到文件all.txt

这是我到目前为止的代码,但它没有输出任何内容:

 #!/bin/bash
    echo This goes to stdout
    echo And this is and error going to stderr 1>&2
    exec 1>output.txt
    exec 2>error.txt
    exec >all.txt 1>&2

1 个答案:

答案 0 :(得分:1)

您可以将tee命令与process substitution组合使用。

#!/bin/bash

exec 3> all.txt # fd3 goes to all.txt
exec 1> >(tee output.txt >&3) # fd1(stdout) goes to both output.txt and fd3
exec 2> >(tee error.txt >&3) # fd2(stderr) goes to both error.txt and fd3

echo Go To Stdout # goes to fd1, and fd1 goes to both output.txt and fd3 (which goes to all.txt)
echo Go To Stderr >&2 # goes to fd2, and fd2 goes to both error.txt and fd3 (which goes to all.txt)