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
}
$@
Executing
. 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
How can a sub-shell process can access the variables and functions initialised in the parent shell?
Adding
export
should do the work:https://www.tutorialspoint.com/unix_commands/export.htm
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.Parentheses gives a subshell. The variable
BASH_SUBSHELL
gives the level of subshell, and$$
gives thePID
of the shell (in subshells it is faked to be the PID of the parent).When you execute a script, that is not a subshell. Take a script
gash.sh
with:Running it as:
Notice the blank because
x
is not copied. It is not a subshell, and the PID is different. Eventhat is a subshell running a child process, so that doesn't work either.
You need to move the variable to the environment block, which is copied to child processes, using
export
:Variables that are not exported are only available in subshells using
( )
, not other child processes. For functions useexport -f
.