将stdout和stderr恢复为默认值 [英] Restoring stdout and stderr to default value

查看:63
本文介绍了将stdout和stderr恢复为默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  exec 1>outputfile

但是,如果要在同一脚本中将标准输出描述符"1"恢复为默认值(终端).我们如何实现这一目标?

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

推荐答案

此示例

示例20-2.使用exec重定向标准输出

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

出现以显示您想要的内容.它来自 ABS ,其中有少量讨论和其他相关信息.

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

这篇关于将stdout和stderr恢复为默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆