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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17852801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:01:34  来源:igfitidea点击:

How to let bash subshell to inherit parent's set options?

linuxbash

提问by dspjm

Let's say I do set -xin a script “a.sh”, and it invokes another script “b.sh”.

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

Is it possible to let “b.sh” inherit the -xoption from “a.sh”?

是否可以让“b.sh”继承“a.sh”的-x选项?

回答by rgiar

export SHELLOPTS

for example:

例如:

echo date > b
chmod +x b

without the export, we only see the commands in ./awhen it calls ./b:

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

$ echo ./b > a
$ bash -xv a

./b
+ ./b
Sun Dec 29 21:34:14 EST 2013

but if we export SHELLOPTS, we see the commands in ./aand ./b

但是如果我们导出 SHELLOPTS,我们会在./a./b

$ echo "export SHELLOPTS; ./b" > a
$ bash -xv a

./b
+ ./b  date
++ date   
Sun Dec 29 21:34:36 EST 2013

回答by chepner

Since -xis not inherited by subshells, you need to be a bit more explicit. You can test when -xis used with the $-special parameter.

由于-x不是由子shell继承的,因此您需要更加明确。您可以测试 when-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

回答by Joe

They would be incorporated in script b if script b sourcesscript a. Which may or may not solve your problem for you!

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

回答by Antarus

Like @devnull said you can use .operation in your script.

就像@devnull 说的,您可以.在脚本中使用操作。

In a.sh

在.sh

. SETVALUES

. SETVALUES

In b.sh

在 b.sh

. SETVALUES

. SETVALUES

In SETVALUES

在 SETVALUES

set -x

set -x

Where ever you invoke SETVALUES, those values will be set in that sub shell.

无论您在何处调用 SETVALUES,这些值都将在该子 shell 中设置。