[Discuss] Bourne Shell variable assignment question

Peter Doherty peterd at acranox.org
Thu Dec 15 16:25:38 EST 2011


On Dec 15, 2011, at 15:57 , Jerry Feldman wrote:

> I have not done my homework on this as much as I should.
> A coworker needs to set variable names and values input from another
> file. Normally, I would source that file, but he specifically wants to
> parse the file.
> So, in simple terms, he has a file that has something like:
> var1=foo
> 
> Instead of sourcing he wants to parse the file using readline so he
> reads the variable name, then he wants to assign a variable of the same
> name.
> So, in his code he has something like
> readline
> ... - code to parse the line
> Where varname contains the variable name(eg var1), and value contains
> the value(eg foo)


Matt's suggestion calls grep and cut for each variable.  This creates a lot of process churn, and will become a slowdown if you have a huge number of variables.  But you probably don't.

Are you restricted to Bourne, or can you use BASH?

I know BASH can do fancy string manipulation, but I don't think it's doable in Bourne.
In BASH, i'd do something like this: (assuming I understood your question correctly)

(my input file)
$> cat file 
var1=foo
var2=bar
var3=badidea

(my one liner)
$> while read line ; do export ${line%%=*}=${line#*=} ; done < file 


refs:
http://linuxgazette.net/18/bash.html

Of course, one has to ask why your co-worker is doing this, and not just sourcing the file.
Also, my example will break if you have an equal sign in your variable name or value name.


-peter


More information about the Discuss mailing list