子外壳程序进程无法访问父外壳程序中定义的变量和函数 [英] Sub-shell process not be able to access variables and functions defined in parent shell
问题描述
我在同一目录中有3个脚本,请在下面找到x.sh,y.sh和z.sh的内容:-
I have 3 scripts in the same directory, please find below contents of x.sh, y.sh and z.sh :-
x.sh:-
xData="DataOfX"
function xInit(){
echo "xInit : data of a >$xData<"
}
y.sh:-
. x.sh
xInit
sh z.sh zInit
z.sh:-
function zInit(){
echo "zInit of z"
xInit
}
$@
执行
. y.sh
. y.sh
同一目录中的
给出以下输出:-
in the same directory gives below output :-
xInit : data of a >DataOfX<
zInit of z
z.sh: line 3: xInit: command not found
子shell进程如何访问在父shell中初始化的变量和函数?
How can a sub-shell process can access the variables and functions initialised in the parent shell?
推荐答案
术语"sub-shell"是有问题的,甚至man bash
的使用方式也不一致.严格来说,子shell是另一个shell环境,它继承了父级的所有功能,包括所有变量.
The term "sub-shell" is problematic, and even man bash
is inconsistent in the way it is used. Strictly speaking a sub-shell is another shell environment which inherits all features, including all variables, of the parent.
括号给一个子壳.变量BASH_SUBSHELL
给出子外壳的 level ,而$$
给出外壳的PID
(在子外壳中,它被伪造为父对象的PID).
Parentheses gives a subshell. The variable BASH_SUBSHELL
gives the level of subshell, and $$
gives the PID
of the shell (in subshells it is faked to be the PID of the parent).
$ x=42
$ echo $BASH_SUBSHELL, $x, $$
0, 42, 1130
$ (echo $BASH_SUBSHELL, $x, $$)
1, 42, 1130
$ ( (echo $BASH_SUBSHELL, $x, $$) )
2, 42, 1130
执行脚本时,不是子shell .用以下脚本获取gash.sh
脚本:
When you execute a script, that is not a subshell. Take a script gash.sh
with:
echo $BASH_SUBSHELL, $x, $$
将其运行为:
$ ./gash.sh
0, , 8419
请注意空白,因为未复制x
.它不是子shell,并且PID不同.甚至
Notice the blank because x
is not copied. It is not a subshell, and the PID is different. Even
$ (./gash.sh)
1, , 8421
这是一个运行子进程的子外壳,因此也不起作用.
that is a subshell running a child process, so that doesn't work either.
您需要将变量移动到 environment块,使用export
将其复制到子进程中:
You need to move the variable to the environment block, which is copied to child processes, using export
:
$ export x
$ ./gash.sh
0, 42, 8423
未导出的变量仅在使用( )
的子外壳中可用,而在其他子进程中则不可用.对于功能,请使用export -f
.
Variables that are not exported are only available in subshells using ( )
, not other child processes. For functions use export -f
.
这篇关于子外壳程序进程无法访问父外壳程序中定义的变量和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!