Lets say I have a shell / bash script named test.sh with:
#!/bin/bash
TESTVARIABLE=hellohelloheloo
./test2.sh
My test2.sh looks like this:
#!/bin/bash
echo ${TESTVARIABLE}
This does not work. I do not want to pass all variables as parameters since imho this is overkill.
Is there a different way?
You have basically two options:
export TESTVARIABLE) before executing the 2nd script.. test2.shand it will run in the same shell. This would let you share more complex variables like arrays easily, but also means that the other script could modify variables in the source shell.UPDATE:
To use
exportto set an environment variable, you can either use an existing variable:This ought to work in both
bashandsh.bashalso allows it to be combined like so:This also works in my
sh(which happens to bebash, you can useecho $SHELLto check). But I don’t believe that that’s guaranteed to work in allsh, so best to play it safe and separate them.Any variable you export in this way will be visible in scripts you execute, for example:
a.sh:
b.sh:
Then:
The fact that these are both shell scripts is also just incidental. Environment variables can be passed to any process you execute, for example if we used python instead it might look like:
a.sh:
b.py:
Sourcing:
Instead we could source like this:
a.sh:
b.sh:
Then:
This more or less “imports” the contents of
b.shdirectly and executes it in the same shell. Notice that we didn’t have to export the variable to access it. This implicitly shares all the variables you have, as well as allows the other script to add/delete/modify variables in the shell. Of course, in this model both your scripts should be the same language (shorbash). To give an example how we could pass messages back and forth:a.sh:
b.sh:
Then:
This works equally well in
bash. It also makes it easy to share more complex data which you could not express as an environment variable (at least without some heavy lifting on your part), like arrays or associative arrays.