gpt4 book ai didi

bash - 如何在脚本本身内重定向整个 shell 脚本的输出?

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:58 28 4
gpt4 key购买 nike

是否可以将 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

最佳答案

解决更新后的问题。

#...part of script without redirection...

{
#...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...

#...residue of script without redirection...

大括号“{ ... }”提供了一个 I/O 重定向单元。大括号必须出现在命令可能出现的位置——简单地说,在一行的开头或分号之后。 (是的,可以更精确;如果你想狡辩,请告诉我。)

你是对的,你可以用你展示的重定向保留原始的 stdout 和 stderr,但是对于以后必须维护脚本的人来说,如果你将重定向代码的范围设置为如上所示,通常更容易理解发生了什么.

Bash 手册的相关部分是 Grouping CommandsI/O Redirection . POSIX shell 规范的相关部分是 Compound CommandsI/O Redirection . Bash 有一些额外的符号,但在其他方面类似于 POSIX shell 规范。

关于bash - 如何在脚本本身内重定向整个 shell 脚本的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39012233/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com