在shell脚本中,我们可以使用exec命令将默认输入更改为文件,如下所示:
exec 1>outputfile
但是,如果在同一个脚本中我想要将stdout描述符“1”恢复为默认值(终端)。我们该如何实现?
这个例子
例20-2. 使用exec重定向stdout
#!/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,其中有少量讨论和其他相关信息。
exec | tee outputfile
请查看tee的man页面以获取更多解释:
tee-从标准输入读取并将内容写入标准输出和文件
exec &>/dev/tty
的意思是将标准输出和标准错误输出重定向到当前终端。 - enharmonic