我有一个 bash 脚本,我想用 set -x 捕获脚本的一部分并将该输出重定向到一个文件。
我可以看到 ENVFILE 正在设置的内容,但它会输出。
有没有办法可以将 set -x 的输出捕获到文件而不是 std out 中?
#!/bin/sh
...a bunch of stuff....
if [ -e ${ENVFILE} ]; then
set -x
. ${ENVFILE}
set +x
fi # ! -e PROJOB
... a bunch of stuff ....
Run Code Online (Sandbox Code Playgroud)
如果您使用 bash,则可以使用BASH_XTRACEFD:
...
if [ -e ${ENVFILE} ]; then
BASH_XTRACEFD=3
set -x
. ${ENVFILE}
set +x
unset BASH_XTRACEFD
fi # ! -e PROJOB
...
Run Code Online (Sandbox Code Playgroud)
然后像这样执行脚本:
/path/to/script 3>/path/to/trace.output
Run Code Online (Sandbox Code Playgroud)
如果您已经在使用 FD 3,请使用 3 以外的文件描述符。
小智 0
我会这样做。看一下代码中的注释。
#!/bin/sh
...a bunch of stuff....
if [ -e ${ENVFILE} ]; then
#save the file descriptor of the current stderr
exec 3>&2
#redirect to the file
exec 2>/.../you_file
set -x
. ${ENVFILE}
set +x
#restore original redirection
exec 2>&3
#close file descriptor 3
exec 3>&-
fi # ! -e PROJOB
... a bunch of stuff ....
Run Code Online (Sandbox Code Playgroud)
如果您希望在调试内容旁边重定向标准输出,则需要使用 . 以与 fd 2 类似的方式重定向文件描述符 1 exec
。