将 bash -x 输出发送到日志文件而不中断标准输出

sor*_*ink 16 scripting linux bash debugging

有没有办法通过运行带有 -x 选项的 bash 脚本将显示的信息发送到文件,同时不更改运行脚本的用户看到的标准输出?

这是我想在我们经常使用的 bash 脚本中实现的调试功能。

非常感激。

Sta*_*dog 27

-x 的输出到 stderr,而不是 stdout。但即使这样也可能是一个问题——大量脚本将对 stderr 的内容具有功能依赖性,并且在某些情况下将调试和 stderr 流混合在一起会有点混乱。

Bash 版本 > 4.1 确实提供了一个不同的解决方案: BASH_XTRACEFD 环境变量允许您指定一个文件描述符,该描述符将用于将调试流发送到。这可以是文件或管道,或者您喜欢的任何其他 unix-y 优点。

# Use FD 19 to capture the debug stream caused by "set -x":
exec 19>/tmp/my-script.log
# Tell bash about it  (there's nothing special about 19, its arbitrary)
export BASH_XTRACEFD=19

# turn on the debug stream:
set -x

# run some commands:
cd /etc
find 
echo "Well, that was fun."

# Close the output:
set +x
exec 19>&-

# See what we got:
cat /tmp/my-script.log
Run Code Online (Sandbox Code Playgroud)

稍微摆弄一下,您可以做其他事情——比如在 stdout 和/或 stdin 流上做一个“tee”,并将它们与调试输出交错,这样您的日志就更完整了。有关更多详细信息,请参阅/sf/ask/222119201/

与替代方法相比,这种方法的最大优势在于,您不会因为将调试输出注入 stdout 或 stderr 来冒改变脚本行为的风险。


Sve*_*ven 1

man tee

您像这样运行它tee commandname filename,它将显示命令输出stdout并将其写入filename.