如何让 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
How to let bash subshell to inherit parent's set options?
提问by dspjm
Let's say I do set -x
in 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 -x
option 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 ./a
when 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 ./a
and ./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 -x
is not inherited by subshells, you need to be a bit more explicit. You can test when -x
is 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
回答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 中设置。