1

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.

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.