[英]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. 我正在使用
set -x
在外壳脚本A.sh
实现调试标志:如果我调用A.sh -d
则-d
标志将导致set -x
被调用。 Each line executed in A.sh
is going to be printed to stderr, with a +
prefix. 在
A.sh
执行的每一行都将被打印到带有+
前缀的stderr中。 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. 此时,我正在编写具有相同特征的脚本
B.sh
B.sh -d
还将打印带有+
前缀的每一行。
I would like to call A.sh
from within B.sh
, and to propagate the -d
flag. 我想从
B.sh
调用A.sh
,并传播-d
标志。 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.sh
通过发射和那些B.sh
,因为这两个将启动+
。
A possible solution would be to call A.sh
from within B.sh
as follows: 一种可能的解决办法是打电话
A.sh
内B.sh
如下:
propagate_options='-d'
A.sh $propagate_options 2> >(sed 's/^\+/++/')
But this is somewhat ugly and possibly not very portable. 但这有点丑陋,可能不是很方便。 Any better idea?
有更好的主意吗?
After chepner 's idea I've simply implemented the debug mode as follows: 在chepner的想法之后,我简单地实现了调试模式,如下所示:
PS4="+$(basename $0): "
propagate_options='-d'
set -x
This makes it really easier to understand what is the output of what… 这确实使您更容易理解什么的输出……
set -x
uses the current value of PS4
as the marker for each line of output. set -x
使用PS4
的当前值作为输出每一行的标记。
PS4
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.
当在交互式外壳中执行执行跟踪(设置-x)时,在执行跟踪中的每一行之前,应对该变量的值进行参数扩展并写入标准错误。 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.
POSIX.1-2008的此卷仅对支持用户可移植性实用程序选项的系统指定了变量的影响。
The most 'natural' way is to source the file. 最“自然”的方法是获取文件。 The shell recognizes that, and since you're sourcing debug is propagated.
Shell会识别出这一点,并且由于您正在采购调试信息,因此会传播。 The kick - each source will add a"+" automatically at the beginning.
踢脚-每个来源都会在开头自动添加“ +”。 Here is
a.bash
: 这是
a.bash
:
#!/bin/bash
set -x
echo 1
echo 2
. b.bash
and b.bash
: 和
b.bash
:
#!/bin/bash
echo a
echo b
Running a.bash
results in: 运行
a.bash
导致:
+ echo 1
1
+ echo 2
2
+ . b.bash
++ echo a
a
++ echo b
b
Note the b
commands have two ++
. 注意
b
命令有两个++
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.