Edison Lo
Edison Lo

Reputation: 476

How can i fix the bad substitution?

I got loc_list0,1,2,3, and i try to do it efficiently and type

b=0
while [ $b -lt 4 ]
do
     grep -c "${loc_list$b[0]}" Record$b.txt
done

It says Bad Substitution on ${loc_list$b[0]}, but ok for Record$b. What is the reason behind? I am new to bash shell can anyone tell me how to fix it instead of writing duplicate codes.

Thanks man! But another problems come when i want to use two varibales for iteration thanks man, how about i got two variables b and c which works as counting numbers of iteration such that:

b=0
c=0
while [ $b -lt 5 ]
do
    temp_length=( "${loc_list$b[@]}" )
    while [ $c -lt ${#temp_length[@]} ]
    do
       ...
       c=$((c+1))
    done
 ...
b=$((b+1))
done

how to fix the bad substitution this time?

Upvotes: 1

Views: 1902

Answers (1)

chepner
chepner

Reputation: 531175

You need to use indirect parameter substitution. With arrays, the index you want is considered part of the name.

name=loc_list$b[0]
grep -c "${!name}" Record$b.txt

Record$b.txt works because it is a simple string concatenation, Record + $b + .txt. You aren't try to further expand the result.

Upvotes: 4

Related Questions