Building Variable Names in Bourne Shell

M.T.Russell mtr at eagle.ukc.ac.uk
Thu Mar 24 02:55:41 AEST 1988


In article <12565 at brl-adm.ARPA> kevinc at bearcat.lim.tek.com (Kevin Cosgrove 627-5212) writes:
>Anyone know how to build *accessible* variable names on the fly in Bourne
>shell?

One method is to echo appropriate magic to a file, and then source
that file.  Thus the following Bourne shell fragment

	fred="hello world"
	varname=fred
	echo result=\$$varname > tmpfile
	. tmpfile

sets the variable result to $fred, or "hello world" in this case.

By the way, I find the "." command very useful in shell scripts.
Arguably it's better than shell functions because you get named
parameters - you can do things like

	question="Do you want to load all the software"
	default=yes
	. ask		# ask is a neat script for asking questions
	if [ "$answer" = yes ]; then
		...

where the shell variables question and default are effectively 
parameters to the ask script, and answer is the return value.
You have to be disciplined with variable names though, as all
variables are of course global.

Mark Russell
mtr at ukc.ac.uk



More information about the Comp.unix.wizards mailing list