如何使用 sed 编辑 bash 调试输出?(bash -x)

ait*_*tee 5 scripting bash sed stderr

#!/bin/bash -x
echo This is a script that has debugging turned on
Run Code Online (Sandbox Code Playgroud)

此脚本输出

+ echo This is a script that has debugging turned on
This is a script that has debugging turned on
Run Code Online (Sandbox Code Playgroud)

我想通过删除或替换它们来摆脱这些 +。我希望 sed 可以解决我的问题 ( sed 's/^\++//g') -- 但这种方法不会影响调试输出行。

通过更多的实验,我发现调试输出似乎被写入 stderr(用./test.sh 2>/dev/null输出然后排除调试行的命令推断出这一点)

有了这些新信息,我希望这能奏效 ./test.sh 2>&1 | sed 's/^\++//g'

但是,唉,我仍然得到相同的不想要的输出:

+ echo This is a script that has debugging turned on
This is a script that has debugging turned on
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 15

+PS4提示。将其设置为空字符串:

#!/bin/bash

PS4=''
set -x

echo 'This is a script that has debugging turned on'
Run Code Online (Sandbox Code Playgroud)

测试:

$ bash script.sh
echo 'This is a script that has debugging turned on'
This is a script that has debugging turned on
Run Code Online (Sandbox Code Playgroud)

或者,使用您的原始脚本,PS4在调用脚本时将其设置为空字符串:

$ PS4='' ./script.sh
echo This is a script that has debugging turned on
This is a script that has debugging turned on
Run Code Online (Sandbox Code Playgroud)

这可用于插入时间戳:

$ PS4='$(date +"%T: ")' ./script.sh
21:08:19: echo 'This is a script that has debugging turned on'
This is a script that has debugging turned on
21:08:19: echo 'Now sleeping for 2 seconds'
Now sleeping for 2 seconds
21:08:19: sleep 2
21:08:21: echo Done
Done
Run Code Online (Sandbox Code Playgroud)


Jef*_*ler 5

您遇到的主要限制+扩展正则表达式功能,因此您需要启用扩展正则表达式功能;对于大多数seds,那就是-E标志:

./test.sh 2>&1 | sed -E 's/^\++ //'
Run Code Online (Sandbox Code Playgroud)

我做了另外两个改变:

  • 添加了尾随空格,以便调试的命令显示为左对齐
  • 删除了/g标志,因为正则表达式是锚定的,每行只能有一个匹配项