将stdout和stderr恢复为默认值

时间:2022-04-21 00:07:24

In shell script, We can change the default input to a File using the exec command as follow :

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

  exec 1>outputfile

However, if in the same script if I want to restore the stdout descriptor '1' to the default (terminal). How can we achieve that?

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

2 个解决方案

#1


5  

This example

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

Appears to show what you want. It came from here, where there is a small amount of discussion and other relevant information.

似乎显示你想要的东西。它来自这里,有少量的讨论和其他相关信息。

#2


0  

Try the "tee" command:

试试“tee”命令:

exec | tee outputfile

Look at the tee manpage for more explainations:

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

tee - read from standard input and write to standard output and files

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

#1


5  

This example

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

Appears to show what you want. It came from here, where there is a small amount of discussion and other relevant information.

似乎显示你想要的东西。它来自这里,有少量的讨论和其他相关信息。

#2


0  

Try the "tee" command:

试试“tee”命令:

exec | tee outputfile

Look at the tee manpage for more explainations:

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

tee - read from standard input and write to standard output and files

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