是否可以将 Bourne shell 脚本的所有输出重定向到某个地方,但在脚本本身内部使用 shell 命令?
重定向单个命令的输出很容易,但我想要更像这样的东西:
#!/bin/sh
if [ ! -t 0 ]; then
# redirect all of my output to a file here
fi
# rest of script...
含义:如果脚本以非交互方式运行(例如,cron),则将所有内容的输出保存到文件中。如果从 shell 以交互方式运行,让输出像往常一样转到标准输出。
我想为通常由 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