Bash – Sharing variables across multiple shell scripts

bashshell-script

I am trying to summarize multiple shell scripts within one large shell script, such as this:

#!/bin/sh
bash script1.sh
bash script2.sh
bash script3.sh

All scripts share the same variables var and var2. I wanted to delete the variable definitions from the individual shell scripts and put it into the large shell script instead, so that when I change the value of the variables I only have to do that once.

However, when I do

#!/bin/sh
var1="1"
var2="2"
bash script1.sh
bash script2.sh
bash script3.sh

the variables are not recognised by the references $var1 and $var2 in the individual shell scripts.

Apologies if the question has been asked before, I am new to scripting in general and didn't know what to search for.

It would also be nice to know how I could loop over the scripts with multiple variable inputs, such as

var1="1 2 3 4 5"
var2="a b c d e"
for i in $var1;do for j in $var2;do
script1.sh
script2.sh
done;done

Best Answer

When you run scripts 1-3 inside your main script, they are each run inside their own sub-shell, which is why they don't recognise the variables defined in their parent shell. Use export to make variables available to sub-shells:

#!/bin/sh
export var1="1"
export var2="2"
bash script1.sh
bash script2.sh
bash script3.sh

An alternative (relevant for your second question) would be to pass the variables to the scripts as positional parameters:

#!/bin/sh
var1="1"
var2="2"
bash script1.sh "$var1" "$var2"
bash script2.sh "$var1" "$var2"
bash script3.sh "$var1" "$var2"

Inside scripts 1-3, these variables would then be available as $1 and $2 respectively.