简体   繁体   English

在[ba] sh中传播`set -x`

[英]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.shB.sh如下:

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: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM