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

如何使用 sed 编辑 bash 调试输出? (bash-x)
#!/bin/bash -x
echo This is a script that has debugging turned on

该脚本输出

+ echo This is a script that has debugging turned on
This is a script that has debugging turned on

我想通过删除或替换它们来摆脱这些+。我期望 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

答案1

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

#!/bin/bash

PS4=''
set -x

echo 'This is a script that has debugging turned on'

测试:

$ bash script.sh
echo 'This is a script that has debugging turned on'
This is a script that has debugging turned on

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

$ PS4='' ./script.sh
echo This is a script that has debugging turned on
This is a script that has debugging turned on

这可用于插入时间戳:

$ 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

答案2

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

./test.sh 2>&1 | sed -E 's/^\++ //'

我做了另外两项更改:

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

答案3

您可以将 stderr 重定向到进程替换中。但这可能会影响输出的顺序:

$ bash -x -c 'hostname; echo "$(date)"'
+ hostname
jackmanVM
++ date
+ echo 'Tue Oct 23 15:22:02 EDT 2018'
Tue Oct 23 15:22:02 EDT 2018

$ bash -x -c 'hostname; echo "$(date)"' 2> >(sed -E 's/^\++/debug: /')
debug:  hostname
jackmanVM
debug:  date
Tue Oct 23 15:22:35 EDT 2018
debug:  echo 'Tue Oct 23 15:22:35 EDT 2018'

相关内容