Setting a variable using variables in a loop

Hi,

I am having a bit of trouble with the below code:

file=/path/to/file
for i in 03 06 07 21; do
if [ -f $file-$i ]; then
eval count$i=`grep -c word $file-$i`
fi
done

Totalcount=0
for i in 03 06 07 21; do
if [ ! -z "$count$i" ]; then
echo  $count$i variable not exist;
else Tcount=`expr $Tcount + $count$i`;
fi
done

echo $Tcount

When running it i am getting:

03 variable not exist
06 variable not exist
07 variable not exist
21 variable not exist

file-07 and file-21 exist, but file-03 and file-06 do not.
I am trying check if a file exists, and if it does i need to find how many times a word occurs in the file on separate lines (grep -c) and assign it to a variable. The file will be appended by 03,06,07 or 21. I do not know when each file will exist, but it is possible that all could exist or none, or just a few.

Once i have all the variables populated with the counts, i need to total them up. I do not know which variables would have been created so i need a method of checking if a variable exists.

I have been playing about with this for ages but cannot get it to work.

Any help is appreciated.

Thanks

Does this work for you?

#! /bin/bash

count03=5
count06=3

Tcount=0
for i in 03 06 07 21
do
    wordcnt=$(eval echo \$count$i)
    if [ -z $wordcnt ]
    then
        echo count$i variable does not exist;
    else
        Tcount=`expr $Tcount + $wordcnt`;
    fi
done

echo "Total count is: $Tcount"

If you want all the files that starts with file- , can't you do it this way?

for i in file-* do
if [-f $i ]; then
<change remaining script accordingly>

Just wondering....

Variables do not work that way. You have to use eval to force it, and that's never a good idea.

Why not use an array?