Reputation: 9216
I have to bash scripts:
script1.sh
HELLO=hello
export HELLO
./script2.sh
echo $HELLO
script2.sh
echo $HELLO
HELLO=world
export $HELLO
The output is hello hello
instead of hello world
. How can I modify variables between scripts which call each other?
EDIT: Passing variables as arguments won't work. I don't know the number of variables which might be changed in script2.sh.
Upvotes: 1
Views: 2928
Reputation: 853
When u call new script by ./script2.sh it forks new shell and new shell will be closed when script2 completes execution. When control comes back to script its still old shell so variable exported in script2 wont be available. To run script2 in same shell u have run it like ". ./script2.sh"
HELLO=hello
export HELLO
. ./script2.sh
echo $HELLO
Upvotes: 1
Reputation: 3665
Exported variables are available in subshells (as is the case with script2.sh
vs script1.sh
), but not to parent shells.
For this reason, the variable set by script1.sh
is available in script2.sh
, but setting it in script2.sh
will not make it available in script1.sh
when script2.sh
returns.
If you will to pass the variable back to the caller, you'd need to echo
it, and grab the output of script2.sh
. But then, you'll need script2.sh
to write to stderr if you want to see its output:
script1.sh:
HELLO=hello
export HELLO
HELLO=$(./script2.sh)
echo >&2 $HELLO
script2.sh:
echo $HELLO >&2
HELLO=world
echo $HELLO
Upvotes: 1
Reputation: 241988
If you do not want to run the second script as a child process, you have to source it:
HELLO=hello
export HELLO
. ./script2.sh # Note the dot at the beginning
echo $HELLO
No export is needed in the second script - you already told bash to export the variable.
Upvotes: 3
Reputation:
The environment of script1.sh
contains HELLO=hello
. Nothing you do in the child script2.sh
will change that.
Upvotes: 0