Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Blog | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Discuss] Bourne Shell variable assignment question



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



BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org