我想写一个 bash shell 脚本,将 STDOUT 重定向到文件 "result.log",STDERR+STDOUT 重定向到文件 "complete.log。最好是第三个文件,只有 STDERR suc 作为"错误.log。最后向终端显示标准输出
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
试试这个方式:
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
以下解决方案仅在 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