zsh:重置 stdout/stderr 重定向

标签 zsh file-descriptor io-redirection

我从 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/

相关文章:

zsh 转义反斜杠

c - 使用O_CREAT时open的执行

c - 在 C 中使用运算符 < 从文件重定向

windows - Stream 3 句柄重定向导致输出溢出

command-line - Zsh:从下划线更改行编辑光标?

linux - 为什么别名在/etc/profile 中不可用?

linux - Linux 中的 git 和硬链接(hard link)

linux - Linux 中识别描述符类型

c++ - boost::process 系统泄漏文件描述符

bash - bash 与 zsh 中的重定向和管道行为