PDA

View Full Version : shell script - dynamic variables


rnavanee
07-19-03, 05:42
Assume that there are 3 variables $file1, $file2, $file3
I want to access the values of these variables inside a loop
for i in 1 2 3
do
a=$file$i
...
done


But this is not working as expected ...

Please give me a solution

LKBrwn_DBA
07-19-03, 12:28
Try it with eval:

eval a=$file$i

asuski
07-19-03, 15:38
oh dear where to start .. I do not believe the previous suggestion will work for you. I could not make it work with the bash shell.

if what you are trying to accomplish is simple in that the are always three variables something like the following will work.
for I in "$file1" "$file2" "$file3" ; do echo $I ; done


If have a more dynamic situation, look into bash shell support of array variables. Try this from a bash shell.
If you are using bash 2 it supports array variables try this code snippet.

# Define the FILES array
FILES[1]="file1"
FILES[2]="file2"
FILES[4]="file4"
echo ${FILES } #Display all elements of the array
# show the files of array elements 0-4
I=0
while [ $I -le 4 ] ; do
a=${FILES[$I]}
echo FILES[$I]=$a
I=$(( $I+1 ))
done

pooja
07-21-03, 06:11
Originally posted by rnavanee
Assume that there are 3 variables $file1, $file2, $file3
I want to access the values of these variables inside a loop
for i in 1 2 3
do
a=$file$i
...
done


But this is not working as expected ...

Please give me a solution

hello,

can u tell which shell r u using...as this will work fine in bourne and korn shell.

#!/bin/ksh
file='filename'
for i in 1 2 3
do
a=$file$i
echo $a
done

this will print

filename1
filename2
filename3

pooja

Damian Ibbotson
07-21-03, 08:12
The array solution is probably most appropriate for what you are trying to accomplish here.

However, 'eval' is generally used for dynamic scripting purposes and could be used to achieve what you require.

file1=myfile1
file2=myfile2
file3=myfile3

for i in 1 2 3
do
eval echo \$file$i
done

Will output...

myfile1
myfile2
myfile3

You can eval[uate] code many times before it is passed to the shell...

a=foo
b=bar
foobar=barfoo
barfoo=nonsense
nonsense="sed 's/barfoo/barstool/g'"

echo $a$b
eval echo \$$a$b
eval eval echo \\$\$$a$b
eval echo "\$$a$b | $nonsense"

Would output...

foobar
barfoo
nonsense
barstool

You just nee to be aware of command line processing and how the shell parses the line (and that can be a lot harder than it sounds!).