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 来冒改变脚本行为的风险。