6

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
  • ...maybe put those variables in one shell snippet and "source" them in all scripts? – yeti May 30 '14 at 12:20
10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.