Question

  Asked: May 12 2004   11:18 PM GMT
  Asked by: smooth


How to modify external environment variable from 2nd shell script


Bash, Bourne, KSH

There are two shell scripts. First one creates variable as:
"export VAR1=init_value;" OR "declare -x; VAR1=init_value;"
Second script can read this variable and modifies the variable's value but after exiting the variable still keep original value. What is wrong?

Subscribe to Alerts! Get questions and answers delivered to your Inbox.


E-mail me updates on this question



   SUBSCRIBE

hidden modal window

Answer Wiki (Improve, edit or add to this answer)


 RATE THIS ANSWER
0
Click to Vote:
  •   0
  •  0



Which shell are you using (ksh, bash, etc.) and how are you calling the 2nd script from the 1st script?
  • AddThis Social Bookmark Button

Browse more Questions and Answers on Linux.

Looking for relevant Linux Whitepapers? Visit the SearchEnterpriseLinux.com Research Library.


Discuss This Answer


You must be logged-in to discuss a question. Log-in/Register

smooth  |   May 13 2004  3:47PM GMT

I’m using bash.
Calling 2nd script from the 1st directly by name, like:

#!/bin/bash
#
# this 1st script script1.sh
export Var1=100; # OR declare -xi Var1; Var1=100;


echo $Var1
script2.sh
echo $Var1

EOF
————————
#!/bin/bash
#
# this 2nd script script2.sh


echo $Var1
Var1=$((Var1-1)); or any other arithmetic operation
echo $Var1


EOF

 

nmarco  |   May 13 2004  4:07PM GMT

The problem is that the second script runs in it’s own subprocess. Therefore when the second script ends, the value for $Var1 will be the same as it was before calling the second script.

To overcome this, you can “source” the second script. In bash, this is accomplished with a “.” (period)

Therefore, instead of:

echo $Var1
script2.sh
echo $Var1

try this:

echo $Var1
. script2.sh
echo $Var1

 

smooth  |   May 13 2004  8:52PM GMT

Just took a look to “man .”; will try. Thank you for tip, nmarco!