Passing arguments from one script to another
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 thefile
variable is not necessary, you could also simplysource "$1"
but I have written it this way in an attempt to show how positional parameters are handled
Related videos on Youtube
![ctrl-alt-delor](https://i.stack.imgur.com/DZUB4.png?s=256&g=1)
ctrl-alt-delor
A software engineer, programmer, project manager, Gnu+Linux user, Newly Qualified Teacher of computing. I am currently hanging out on A new site for computer science and IT educators. Visit the site here
Updated on September 18, 2022Comments
-
ctrl-alt-delor over 1 year
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.
-
αғsнιη about 5 yearsplease also read stackoverflow.com/q/5228345/4023950
-
-
Admin about 5 yearsI 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.
-
user394 almost 5 yearslol why is the last part hidden? Is it a spoiler? XD