将stdout和stderr恢复为默认值

Nav*_*lam 8 linux shell redirect stdout exec

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

  exec 1>outputfile
Run Code Online (Sandbox Code Playgroud)

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

Gre*_*ade 8

这个例子

#!/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
Run Code Online (Sandbox Code Playgroud)

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

  • 好,我知道了。我们将默认STDOUT存储在6中,然后将其从6恢复。这就是我一直在寻找的东西。此外,您在评论中提供的链接也有很大帮助。谢谢。 (2认同)