2

Let's say I am in a Bash script and am sourcing a file. How do I pass variables to another script after I source the file like this.

sed -i 's/ = /=/' $file
source $file

Let's say file contains

variable1=10
variable2=apple

If I want to use these in another script, how do I pass these arguments to the other script, then run the script in my current Bash script.

1

2 Answers 2

4

You would pass them pretty much the same as you would pass arguments in any other way:

sed -i 's/ = /=/' "$file"
source "$file"

/path/to/another/script.sh "$variable1" "$variable2"

Obviously using the appropriate command line switches (or not if applicable).

If using the code as above, the value of $variable1 will be available in the other script as $1 (the 1st command line argument), while $variable2 will be available as $2.

To keep the original names in your new script you would need to reassign them using the positional parameters, ie:

variable1=$1
variable2=$2

However this may not be the most efficient way to do this, you might be better off with the suggestion below:


It sounds like you may actually want to source your file within the second script and not the first. In which case you may want to do the following:

script1.sh:

sed -i 's/ = /=/' "$file"
/path/to/another/script2.sh "$file"

script2.sh:

file=$1
source "$file"
printf '%s\n' "$variable1"
printf '%s\n' "$variable2"

Related recommended reading: 3.4.1 Positional Parameters

Note: assigning $1 to the file variable is not necessary, you could also simply source "$1" but I have written it this way in an attempt to show how positional parameters are handled

3
  • I tried this (no necessary switches) and it's not working. The "another" script is running, because if I set the other script simply to "echo apple", it will display "apple", but if I set the other script to simply "echo $variable1", it displays a blank line. I know $variable1 has a value, because if I do "echo $variable1" before calling the other script, I get the proper value, so it seems that the variable is not getting passed.
    – user317784
    Mar 16, 2019 at 16:29
  • Is there something I need to do in the second script to receive $variable1 ?
    – user317784
    Mar 16, 2019 at 16:30
  • lol why is the last part hidden? Is it a spoiler? XD
    – user394
    May 10, 2019 at 19:07
0

If there aren't too many variables you want to pass, it's reasonable to just set them on the line where you call the subscript:

sed -i 's/ = /=/' "$file"
source "$file"

variable1=$variable1 variable2=$variable2 /path/to/another/script.sh

You must log in to answer this question.