我从 zsh 手册页中收集到的一些有趣的东西是如何将 stdout 和 stderr 重定向到其他地方,例如一份文件。它的工作原理如下:
logfile=/tmp/logfile # Create a file descriptor and associate it with the logfile integer logfd exec {logfd} >> ${logfile} echo "This goes to the console" echo "This also goes to the console" >&2 echo "This goes to the logfile" >&{logfd} # Now redirect everything to stdout and stderr to the logfile # No output will be printed on the console exec >&${logfd} 2>&1 print "This goes to the log file" print "This also goes to the log file" >&2
为了完整起见,可以通过发出 exec {logfd}>&-
来关闭文件描述符。
我就是想不通一件事。如何重置 zsh 的重定向,以便将进一步的输出再次打印到控制台?
最佳答案
在我发出ls -l/proc/self/fd/
后找到了它。显然有一个文件描述符0
可以使用,它指向控制台。
所以,首先我们重定向回该文件描述符:
exec >&0 2>&1
现在可以安全地关闭日志文件了:
exec {logfd}>&-
非常适合脚本。
关于zsh:重置 stdout/stderr 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21923111/