将 -x 调试命令捕获到 Bash 中的文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25593034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:15:55  来源:igfitidea点击:

Capture -x debug commands into a file in Bash

bashdebugging

提问by Ondra ?i?ka

Using set -xin bash prints the shell-expanded commands to stderr. I would like to redirect these to a file or pipe. But not the whole output - only some commands. Something like:

set -x在 bash 中使用将 shell 扩展命令打印到 stderr。我想将这些重定向到文件或管道。但不是整个输出 - 只有一些命令。就像是:

set -x command.txt  ### <-- command.txt param is made up
echo $A $B
set +x

This would put the debug output to command. txt.

这会将调试输出置于命令中。文本。

Can this be done?

这能做到吗?

回答by Cyrus

With bash4.1 or later:

使用bash4.1 或更高版本:

#!/bin/bash

exec 5> command.txt
BASH_XTRACEFD="5"

echo -n "hello "

set -x
echo -n world
set +x

echo "!"

Output to stdout (FD 1):

输出到标准输出(FD 1):

hello world!

Output to command.txt (FD 5):

输出到 command.txt (FD 5):

+ echo -n world
+ set +x