如何在bash脚本中将STDOUT发送到文件,将STDOUT + STDERR发送到另一个文件?

时间:2019-03-25 15:32:11

标签: bash redirect stdout stderr

我想编写一个bash shell脚本,将STDOUT重定向到文件“ result.log”,将STDERR + STDOUT重定向到文件“ complete.log”。 最好的是第三个文件,只有STDERR suc为“ error.log。 最后将STDOUT显示到终端

Linux Mint 19.1

#!/bin/bash
exec  > >(tee -a result.log full.log) 
exec 2>>full.log 
echo "This is stdout" 
echo "This is stderr" >&2 
echo "This is stdout 2" 
echo "This is stderr 2" >&2 
echo "This is stdout 3" 
echo "This is stderr 3" >&2 
echo "This is stdout 4" 
echo "This is stderr 4" >&2 

输出

full.log:This is stderr 
full.log:This is stderr 2
full.log:This is stderr 3 
full.log:This is stderr 4
full.log:This is stdout
full.log:This is stdout 2
full.log:This is stdout 3
full.log:This is stdout 4
result.log:This is stdout
result.log:This is stdout 2
result.log:This is stdout 3
result.log:This is stdout 4

预期

full.log:This is stdout
full.log:This is stderr
full.log:This is stdout 2
full.log:This is stderr 2
full.log:This is stdout 3
full.log:This is stderr 3
full.log:This is stdout 4
full.log:This is stderr 4
result.log:This is stdout
result.log:This is stdout 2
result.log:This is stdout 3
result.log:This is stdout 4

2 个答案:

答案 0 :(得分:0)

尝试一下:

exec 1> >(tee -a result.log >>full.log)
exec 2>>full.log

但是请考虑,full.log中的输出顺序现在是:

This is stderr
This is stderr 2
This is stderr 3
This is stderr 4
This is stdout
This is stdout 2
This is stdout 3
This is stdout 4

答案 1 :(得分:0)

仅当bash支持/dev/fd/NUM时,以下解决方案才有效。它将输出保持顺序。

#!/bin/bash
exec 1>>result.log 2>>full.log

echo "This is stdout"   | tee -a /dev/fd/2
echo "This is stderr"   >&2 
echo "This is stdout 2" | tee -a /dev/fd/2
echo "This is stderr 2" >&2 
echo "This is stdout 3" | tee -a /dev/fd/2
echo "This is stderr 3" >&2 
echo "This is stdout 4" | tee -a /dev/fd/2
echo "This is stderr 4" >&2