如何让 bash 子壳继承父级的设置选项?



假设我在脚本"a.sh"中执行set -x,它调用另一个脚本"b.sh"。

是否可以让"b.sh"从"a.sh"继承-x选项?

export SHELLOPTS

例如:

echo date > b
chmod +x b

如果没有导出,我们只能在./a调用./b:时看到命令

$ echo ./b > a
$ bash -xv a
./a
+ ./b
Sun Dec 29 21:34:14 EST 2013

但是如果我们导出SHELLOPTS,我们会在./a./b 中看到命令

$ echo "export SHELLOPTS; ./b" > a
$ bash -xv a
./a
+ ./b  date
++ date   
Sun Dec 29 21:34:36 EST 2013

由于-x不是由子shell继承的,因此需要更加明确一点。您可以测试-x何时与$-特殊参数一起使用。

if [[ $- = *x* ]]; then
    # Set the option, then *source* the script, in a subshell
    ( set -x; . b.sh )
else
    # Simply run the script; subshell automatically created.
    ./b.sh
fi

如果脚本b来源于脚本a,它们将被合并到脚本b中。这可能会也可能不会为您解决问题!

Like@devnull说您可以在脚本中使用.操作。

在a.sh 中

. SETVALUES

b.sh

. SETVALUES

设定值

set -x

无论在哪里调用SETVALUES,这些值都将在该子shell中设置。

最新更新