Bash – How to use sed to edit bash debug output? (bash -x)

bashscriptingsedstderr

#!/bin/bash -x
echo This is a script that has debugging turned on

This script outputs

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

I want to get rid of these +'s by deleting them or replacing them. I expected sed could fix my problem (sed 's/^\++//g') — But this approach doesn't affect the debug output lines.

With some more experimenting, I discovered that the debug output seems to be getting written to stderr (inferred this with the command ./test.sh 2>/dev/null which the output then excludes the debug lines)

With this new information, I would expect this to work
./test.sh 2>&1 | sed 's/^\++//g'

But, alas, I still get the same undesired output:

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

Best Answer

The + is the PS4 prompt. Set it to an empty string:

#!/bin/bash

PS4=''
set -x

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

Testing:

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

Or, with your original script, set PS4 to an empty string for the script when invoking it:

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

This could be used to insert a timestamp:

$ 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
Related Question