简体   繁体   中英

Overriding a variable in two bash scripts

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.

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.

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

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

The environment of script1.sh contains HELLO=hello . Nothing you do in the child script2.sh will change that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM