Dacav
Dacav

Reputation: 14078

Propagate `set -x` in [ba]sh

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…

Upvotes: 1

Views: 893

Answers (3)

kabanus
kabanus

Reputation: 25895

The most 'natural' way is to source the file. The shell recognizes that, and since you're sourcing debug is propagated. The kick - each source will add a"+" automatically at the beginning. Here is a.bash:

set -x   

echo 1
echo 2
. b.bash

and b.bash:

echo a
echo b

Running a.bash results in:

+ echo 1
1
+ echo 2
2
+ . b.bash
++ echo a
a
++ echo b
b

Note the b commands have two ++.

Upvotes: 1

Denis M
Denis M

Reputation: 81

PS4="+$(basename $0): "

i use this that i found somewhere :

exec {BASH_XTRACEFD}>>"path/trace.dbg"
set -x
PS4='[$(basename ${BASH_SOURCE[0]:-inherited}):${LINENO}:${FUNCNAME[0]:-main}] '

Upvotes: 0

chepner
chepner

Reputation: 531295

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.

Upvotes: 3

Related Questions