有没有办法将运行带-x选项的bash脚本显示的信息发送到文件,而不会更改运行脚本的用户看到的标准输出?
这是一个debuggingfunction,我想在一个bash脚本中实现我们经常使用的变化。
非常感激。
-x的输出转到stderr,而不是stdout。 但是即使这样也会成为一个问题 – 大量的脚本将会在stderr的内容上有function依赖,在某些情况下会让debug和stderrstream混在一起。
Bash版本> 4.1提供了一个不同的解决scheme:BASH_XTRACEFD环境variables允许你指定一个文件描述符,用来发送debuggingstream。 这可以是一个文件或pipe道或任何其他你喜欢的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
稍微摆弄一下,你可以做其他事情 – 比如在stdout和/或stdinstream上做一个“tee”,然后把它们与debugging输出交叉,这样你的日志就更完整了。 有关更多详细信息,请参阅https://stackoverflow.com/questions/3173131/redirect-copy-of-stdout-to-log-file-from-within-bash-script-itself 。
这种方法相对于其他方法的一大优点是,通过在stdout或stderr中注入debugging输出,不会冒险改变脚本的行为。
set -x不会向标准输出发送任何东西,所以这里没有问题。 它所做的就是写入标准错误,默认情况下会转到控制台。
你想要做的是将stdoutredirect到另一个文件,如下所示:
/bin/sh -x /my/script/file 2>/my/log/file
见man tee 。
你运行它像tee commandname filename命令tee commandname filename ,它会显示命令输出到stdout并写入到filename 。