Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing variables between two independent shell scripts

Tags:

bash

shell

I am trying to export a variable from one script and use it in another script but this variable is not being exported what might be the problem

Consider this as script1

#!/bin/sh
export x=19
exit 0

Consider this as script2

#!/bin/sh
echo "x="${x}
exit 0

i am executing them as two independent scripts like

desktop:~/Desktop/Trail_Programs$ sh script1.sh
desktop:~/Desktop/Trail_Programs$ sh script2.sh

and output is

desktop:~/Desktop/Trail_Programs$ sh script2.sh 
x=
like image 895
Ap.padole Avatar asked Dec 05 '25 14:12

Ap.padole


1 Answers

Remember a script may NEVER affect its parent's environment. NEVER means NEVER. So following the rule:

#!/bin/bash
export x=19
exit 0

has NO effect on the environment and does not set x=anything there. The export would only affect the environment of subshells created from within that script. For example take your script, call it exp.sh:

#!/bin/bash
export x=19
./script2.sh
exit 0

and in script2.sh you have:

echo "x = $x"

Then, and only then, will you get:

$ bash exp.sh
x = 19

That's just the rule...

like image 136
David C. Rankin Avatar answered Dec 08 '25 06:12

David C. Rankin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!