将stdout和stderr恢复为默认值

时间:2014-01-14 05:09:50

标签: linux shell redirect exec stdout

在shell脚本中,我们可以使用exec命令将默认输入更改为File,如下所示:

  exec 1>outputfile

但是,如果我想在同一个脚本中将stdout描述符'1'恢复为默认值(终端)。我们怎样才能做到这一点?

2 个答案:

答案 0 :(得分:6)

这个例子

Example 20-2. Redirecting stdout using 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

似乎显示您想要的内容。它来自here,其中有少量讨论和其他相关信息。

答案 1 :(得分:0)

尝试“tee”命令:

exec | tee outputfile

请查看tee联机帮助页以获取更多解释:

  

tee - 从标准输入读取并写入标准输出和文件