理解 exec > >(command)

Log*_*Lee 4 bash

我正在尝试了解exec > >(tee logfile)以下代码中的效果:

#!/bin/bash                                                                                                                 

exec 7>&1           # save stdout for later reset                                                                           

exec > >(tee logfile)          # point stdout to FIFO pointing to tee command?                                              
#+expect any subsequent output to stdout to be sent                                                                         
#+both to stdout and logfile.                                                                                               

# so let's send some output                                                                                                 
echo
echo howdy             # expect these strings to be sent both to terminal and                                               
echo g\'day            #+logfile                                                                                            
echo hello!

# restore stdout                                                                                                            
exec 1>&7
exec 7>&-

#check content of logfile!                                                                                                  
echo ------------
cat logfile
Run Code Online (Sandbox Code Playgroud)

我只是在这里猜测这exec > >(tee logfile)会将标准输出重定向到>(tee logfile).

这是运行此脚本时终端的输出:

--------------------

howdy
g'day
hello!

howdy
g'day
hello!
Run Code Online (Sandbox Code Playgroud)

这是日志文件的内容:


howdy
g'day
hello!
Run Code Online (Sandbox Code Playgroud)

看来我试图将stdout回终端没有任何影响:exec 1>&7。也许,exec 1>&7在写入日志文件并将其内容发送到终端之后发生。

而且我不明白执行脚本时终端的输出。我猜exec > >(tee logfile)cat logfile阅读之前被阻止了。然后日志文件的内容由于tee logfile.

你能帮我理解这些要点吗?

谢谢。

Ste*_*ris 5

命令的一般形式是exec > output将所有进一步输出到 stdout 的输出发送到文件“输出”。

这可以扩展;例如exec 2> error将导致所有进一步输出到 stderr 被发送到文件“错误”

现在,>(...)是一种bashism,意思是将输出写入命令;在这种情况下,命令是“tee logfile”

所以我们将两者相加。

exec > >(tee logfile)表示“将所有进一步的输出写入命令tee logfile”。

这意味着所有未来的输出都将发送到屏幕(通过tee)发送到文件“logfile”