Issue
I'm using set -x
to implement a debug flag in a shell script A.sh
: if I call A.sh -d
the -d
flag will result in set -x
being called.
Each line executed in A.sh
is going to be printed to stderr, with a +
prefix. So far so good.
At this point I'm writing a script B.sh
which has the same characteristics: B.sh -d
will also print each line with a +
prefix.
I would like to call A.sh
from within B.sh
, and to propagate the -d
flag.
And here we got the problem: it will be impossible to distinguish between the commands emitted by A.sh
and the ones emitted by B.sh
, since both will start with +
.
A possible solution would be to call A.sh
from within B.sh
as follows:
propagate_options='-d'
A.sh $propagate_options 2> >(sed 's/^\+/++/')
But this is somewhat ugly and possibly not very portable. Any better idea?
Edit
After chepner's idea I've simply implemented the debug mode as follows:
PS4="+$(basename $0): "
propagate_options='-d'
set -x
This makes it really easier to understand what is the output of what…
Solution
set -x
uses the current value of PS4
as the marker for each line of output.
PS4
When an execution trace (set -x) is being performed in an interactive shell, before each line in the execution trace, the value of this variable shall be subjected to parameter expansion and written to standard error. The default value is "+ ". This volume of POSIX.1-2008 specifies the effects of the variable only for systems supporting the User Portability Utilities option.
Answered By - chepner Answer Checked By - Willingham (WPSolving Volunteer)