Linux 将stdout和stderr恢复为默认值
在shell脚本中,我们可以使用exec命令将默认输入更改为文件,如下所示:Linux 将stdout和stderr恢复为默认值,linux,shell,redirect,exec,stdout,Linux,Shell,Redirect,Exec,Stdout,在shell脚本中,我们可以使用exec命令将默认输入更改为文件,如下所示: exec 1>outputfile 但是,如果要将标准输出描述符“1”恢复为默认值(终端),则在同一脚本中。我们如何才能做到这一点 试试“tee”命令: 查看tee手册页了解更多说明: tee-从标准输入读取并写入标准输出和文件 这个例子 例20-2。使用exec重定向标准输出 #!/bin/bash # reassign-stdout.sh LOGFILE=logfile.txt exec 6>
exec 1>outputfile
但是,如果要将标准输出描述符“1”恢复为默认值(终端),则在同一脚本中。我们如何才能做到这一点 试试“tee”命令:
查看tee手册页了解更多说明:
tee-从标准输入读取并写入标准输出和文件
这个例子
例20-2。使用exec重定向标准输出
#!/bin/bash
# reassign-stdout.sh
LOGFILE=logfile.txt
exec 6>&1 # Link file descriptor #6 with stdout.
# Saves stdout.
exec > $LOGFILE # stdout replaced with file "logfile.txt".
# ----------------------------------------------------------- #
# All output from commands in this block sent to file $LOGFILE.
echo -n "Logfile: "
date
echo "-------------------------------------"
echo
echo "Output of \"ls -al\" command"
echo
ls -al
echo; echo
echo "Output of \"df\" command"
echo
df
# ----------------------------------------------------------- #
exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
echo
echo "== stdout now restored to default == "
echo
ls -al
echo
exit 0
显示您想要的内容。它来自,这里有少量的讨论和其他相关信息。请解释您的答案。请提供一些参考,说明您为什么建议这样做。您的建议是将相同的输出重定向到标准输出和输出文件。但是,这与将STDOUT恢复为默认值无关。您能解释一下在上面的示例中我们从何处获得文件描述符“6”吗?正如我指向的文档中所提到的,shell实际上提供了10个编号的文件描述符,以这种方式使用,前三个描述符分配给stdin STDOUT和stderr。它还指出,有一些很好的理由不使用“5”,因为它是由子进程继承的。好的,我知道了。我们将默认标准输出存储在6中,然后将其从6恢复回来。这就是我一直在寻找的。此外,你在评论中提供的链接也很有帮助。谢谢。ABS不是很好的参考资料。这个答案是正确的,但也许它可以链接到更权威和/或可靠的来源
#!/bin/bash
# reassign-stdout.sh
LOGFILE=logfile.txt
exec 6>&1 # Link file descriptor #6 with stdout.
# Saves stdout.
exec > $LOGFILE # stdout replaced with file "logfile.txt".
# ----------------------------------------------------------- #
# All output from commands in this block sent to file $LOGFILE.
echo -n "Logfile: "
date
echo "-------------------------------------"
echo
echo "Output of \"ls -al\" command"
echo
ls -al
echo; echo
echo "Output of \"df\" command"
echo
df
# ----------------------------------------------------------- #
exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
echo
echo "== stdout now restored to default == "
echo
ls -al
echo
exit 0