Use of "eval" in creating new variable names

paul.d.finkel pfinkel at cbnewsb.cb.att.com
Tue May 14 04:05:47 AEST 1991



What follows is part of a script designed to use a program that allows 
simultaneous user-to-user communication. The shell program is supposed
to display a list of users and their ttys. Each line on the list
will begin with a number that is supposed to be used as a means of
eventually identifying their tty.

What I want to do is this: create a bunch of environmental variables that
contain the name of a tty. In my script, this information will be in $2.
I want the names of the variables to include a number ( the same number
displayed on the screen for that particular user).

Example:
The first line might be->    1)joey	tty17	
THe second line              2)les	tty90 
The third line               2)mel	tty99 

I want to create a variable called "tty_numb1" associated with that user.
The contents of the variable will be "tty17".

The following variables will be called "tty_numb2","tty_numb3",etc.

I want to use my variable "count" to bump up the name of these variables so
that later on, when I prompt the user for a number, his response will allow
me to use the variable that contains that same number.

I have tried things like: eval tty_numb"$count"=`echo $2`
If I then try to echo the contents of my new variable, all I get is the number:

Example: echo $tty_numb"$count"    This will give me    1
	                  
If, as a test, I use the number contained by my "count" variable in my 
new variable name, I find that the correct data is being stored where I 
expect it. Example: echo $tty_numb1   This will give me  tty17

If I don't use the "eval" command in my original assignment of a value to my
variable, the shell will balk:

Example: tty_numb"$count"=`echo $2`   This will give me:

					sh: tty_numb1=tty17 not found
Here is the script minus the line(s) needed. If you could help, I'd appreciate it, very much. I am running KSH on a 3B2/600 with UNIX V 3.2.

################################################################################
count=1
who|tr -s " "|cut -f1,2 -d" "|while read line
do
set $line
if [ -w /dev/$2 -a $1 != $LOGNAME ]
then
echo "${count})	$1	$2"
# This is where the assigning of variables should
# take place.
count=`expr "$count" + 1`
fi
done
############################################################################
echo "Enter tty number: \c"
read numb
echo $tty_numb"$numb" #This where the user chooses a number associated with
	              #the desired tty. 



More information about the Comp.unix.shell mailing list