Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi Guys, I'm new to sheel scripting in linux and having some trouble with the following.
I have a file that is in the format
var1=xxx
var2=yyy
var3=zzzwhat I want to do is parse this line by line and then export each as a shell variable to use in other scripts.
I've taken a look at awk to do it and I can get each portion of it out using
awk -F"=" '{print $1;print$2}' /root/server.cfg
however from here im stuck getting it to then export the variables to the shell.
I guess I have 2 questions. can i export these variable out of the awk command to the shell? and is awk the right tool for the job?
dave

If you are saying that you are new to shell
scripting in Linux, exporting a variable is
simple. bash includes the export command.
Simply add a line to export your variables
as follows:var1=xxx
var2=yyy
var3=zzzexport var1 var2 var3
See the manual page for export in a terminal
window with:man export
HTH,
Ernie Registered Linux User 247790
ICQ 41060744

In a shell script, if the data is of the format var=something, it's customary to use the eval command:
#!/bin/bash
while read line
do
eval $line
done < myfileecho $var1
echo $var2
echo $var3

Thanks guys. However, I think i was a bit unclear
I have a server.cfg file that will have a number of variables in it that are specific to the build of a host. These will be used during the post install scripts that are required to run for configuration or installation of software on the host.
This file will be in the format i specified above, but the number and names of the variables may change between each server depending on what is required to be on that server. this file will ultimately be generated by another system so I cant just set them in each script, they need to be centralised in the single server.cfg
So what I want to do at the start of each my customisation scripts is call a little piece of code that will read through each line of the server.cfg, then set (export) each one as a variable and then my script can run and use what ever variables it requires.
I understand how to set variables its just the handling of this file and parsing it to set each one until the eof.

ok i think i have accomplished it with the following
#!/bin/sh
# Extract all variables from server.cfg
cat $serverconfig | sed 's/^/export /' > $varsscript
# Make the script executable
chmod +x $varsscript
source $varsscript<more code inserted here>

There's always more than one way of doing things. eval still does the trick:
#!/bin/bash
while read line
do
eval "export $line"
done < myfile.txtecho $var1
echo $var2
echo $var3BTW, when sourcing a file, I see no reason to make the file executable. Every shell I've worked with, csh, sh, ksh the file only has to be readable.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |