Redirect a COPY of stdout to different log files multiple times from within same bash script

最后都变了- 提交于 2019-12-22 11:29:31

问题


Following line works well when we want to redirect the stdout to a file, and also get printed on stdout.

exec > >(tee logfile-1.txt)

However, if we wish to later redirect the stdout to another file, say,

exec > >(tee logfile-2.txt)

the issue faced is that the output still keeps getting redirected to the first file (logfile-1.txt) along with the second file (logfile-2.txt).

Is there a way that the same bash script contains both the statement, and the output be exclusive to each of the files corresponding to the order of execution of these commands?

Note: This question is in extension to the solution for the question asked here.


回答1:


I'd do

{
    command1
    command2
} | tee logfile-1.txt

{
    command3
    command4
} | tee logfile-2.txt

Alternatively, backup the original filedescriptor, first:

exec 6<&1
exec > >(tee log1)
echo 1
echo 2
exec 1<&6 6<&-
exec > >(tee log2)
echo 3
echo 4

See http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/x13082.html for many more advanced uses of exec



来源:https://stackoverflow.com/questions/14890473/redirect-a-copy-of-stdout-to-different-log-files-multiple-times-from-within-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!