PDA

View Full Version : moving variables from script to script



cbillson
March 12th, 2013, 01:56 PM
as an example if i call setup1.sh and declare:

a=1
b=2

then launch setup2.sh

a=
b=


is there any way i can carry variables from one script when i call another within it?

Cheers
Chris

The Cog
March 12th, 2013, 02:12 PM
export a=1
export b=2
setup2.sh

cbillson
March 12th, 2013, 02:20 PM
is there any way to take all variables (or current environment) - or is it purely a var by var basis?

schragge
March 12th, 2013, 03:41 PM
current environment
env (http://manpages.ubuntu.com/manpages/precise/en/man1/env.1.html) setup2.sh
Obviously, this won't work for variables defined in another script, but not exported to the environment.

Habitual
March 12th, 2013, 04:57 PM
source setup1.sh in setup2.sh?

cbillson
March 13th, 2013, 12:22 PM
Clearly i'm misunderstanding what has been suggested :(

admin@server1:logs$ cat script1.sh
a=1
b=2
c=3
env ./script2.sh

admin@server1:logs$ sudo cat script2.sh
echo a $a
echo b $b
echo c $c
admin@server1:logs$ sudo ./script1.sh
a
b
c

schragge
March 13th, 2013, 12:38 PM
I'd rather define the variables in another file say common_env.sh, and source it from both your scripts as Habitual suggested:


$ cat common_env.sh
a=1 b=2 c=3


$ cat script1.sh
#!/bin/sh
. ${0%/*}/common_env.sh
echo $0: $a $b $c



$ cat script2.sh
#!/bin/sh
. ${0%/*}/common_env.sh
echo $0: $a $b $c



$ ./script1.sh
./script1.sh: 1 2 3
$ ./script2.sh
./script2.sh: 1 2 3

prodigy_
March 13th, 2013, 01:49 PM
Or you can store vars in a text file and source them from there:

#!/bin/sh

varSave () {
# Appends variable $1 to file $2.
printf "%b\n" "$1=\"$(eval printf "%s" \"\$$1\")\"" >> $2
}

a=1
b=2
c=3

for i in a b c; do
varSave $i ./vars
done


Yeah, this function IS ugly. :) But it works. Now in the second script you only need source ./vars.

schragge
March 13th, 2013, 03:10 PM
@prodigy_
The function can be somewhat simplified by using bash-specific syntax for indirect parameter reference:


#!/bin/bash
varSave () {
printf '%s\n' "$1='${!1}'" >> $2
}