在Bourne shell脚本中,是否可以将所有输出重定向至某个位置,但保留脚本内部的shell命令?
重定向单个命令的输出很容易,但我想要更像这样的东西:
#!/bin/sh
if [ ! -t 0 ]; then
# redirect all of my output to a file here
fi
# rest of script...
意思是:如果脚本以非交互方式运行(例如 cron),请将所有输出保存到文件中。如果从 shell 交互式运行,则像往常一样将输出发送到标准输出(stdout)。
我想为通常由 FreeBSD 周期实用程序运行的脚本执行此操作。它是日常运行的一部分,我通常不想每天在电子邮件中看到它,因此我没有将其发送。但是,如果此特定脚本中的某个内容失败,那对我很重要,我希望能够捕获并发送日常作业中这一部分的输出。
更新:Joshua 的答案是完全正确的,但我还想在整个脚本周围保存和恢复 stdout 和 stderr,可以通过以下方式完成:
# save stdout and stderr to file
# descriptors 3 and 4,
# then redirect them to "foo"
exec 3>&1 4>&2 >foo 2>&1
# ...
# restore stdout and stderr
exec 1>&3 2>&4
exec 1>&3 2>&4 3>&- 4>&-
- Gurjeet Singhexec
上出现了Permission denied
。 - Vince