Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing one shell script variable to another shell script

I am trying to access one script variable from another script for example,

script1.sh:

export a=10
export b=20
echo "testing"
exit

script2.sh:

. script1.sh
echo $a

The problem involved here is its able to access the variable 'a' from the script1 in script2 but its executing all the commands written in script1.sh which is annoying. I just want to access only the exported variables in script1 and donot want to run the commands in script1 while calling that in script2.

Kindly help!

Thanks,
Karthik

like image 713
Karthik Avatar asked Oct 19 '25 02:10

Karthik


1 Answers

What you are trying to do (only get the variables from another script, without executing the commands) is not possible.

Here is a workaround:

Extract the variable declaration and initialisation to a third file, which is then sourced by both.

common-vars:

export a=10
export b=20

script1.sh:

. common-vars
echo "testing"
exit

script2.sh:

. common-vars
echo $a
like image 79
Lesmana Avatar answered Oct 22 '25 03:10

Lesmana



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!