Lolly
Lolly

Reputation: 36372

shellscript reading variables from a file

I am new to shell scripting. I am working on a project where the requirement is like one script file will set the variables and another script file has to get those variables and manipulate it. I am storing the variables from first script into a file and in second script file I am reading it.

In first script file, first.sh , I am doing like

echo "a=6" > test.dat
echo "b=7" >> test.dat
echo "c=8" >> test.dat

I use > for the first variable where it overwrites and for the next values it appends. So the file will have the latest values always.

Is there any better approach than this ?

In the second script file how can read and fill the appropriate values ?

Upvotes: 3

Views: 19152

Answers (4)

linuxexplore
linuxexplore

Reputation: 419

There is always a chance for modification, the method for writing your variable file is good. You can still change that as follows:

echo -e "a=6\nb=7\nc=8" > test.dat

And to read the variable file by your script, you can add following:

source test.dat

or

(My recommendation :-))

. test.dat

Upvotes: 0

William Pursell
William Pursell

Reputation: 212198

In terms of writing the file, there are different approaches. Which is better depends on many factors. One common approach is to use a heredoc:

cat > test.dat << EOF
a=6
b=7
c=8
EOF

Upvotes: 0

Igor Chubin
Igor Chubin

Reputation: 64563

You can load this variables from the script using source:

source test.dat

or just

. test.dat

Example:

$ echo "a=6" > test.dat ; echo "b=7" >> test.dat ; echo "c=8" >> test.dat
$ cat test.dat 
a=6
b=7
c=8
$ . test.dat
$ echo $a $b $c
6 7 8

If you have a script/program that generates these variables, you can also use eval.

Example:

$ cat generate.sh
echo a=6
echo b=7
echo c=8

$ bash generate.sh 
a=6
b=7
c=8

$ eval $(bash generate.sh)
$ echo $a $b $c
6 7 8

Upvotes: 10

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

For reading the variables in the second script, you simply need to source it (import it):

## Put this line in your second script
. test.dat

Upvotes: 1

Related Questions