7

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

2 Answers 2

15

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.

1
  • Note that if you want changes made to the variables by any of the child scripts to persist then you should use "source" in place of "bash",
    – symcbean
    Jun 16, 2023 at 14:00
-1

I tried this:

setup_env

var1="1"
var2="2"

script.sh

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

script*.sh

source setup_env
...
2
  • To all the downvoters, may I know why? I can try to correct it.
    – dmachop
    Nov 21, 2023 at 18:42
  • sorry don't know much about your problem, but there are people on here who enjoy the power to downvote others where possible. They don't care to help.
    – matt
    Jan 4 at 1:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .