Aviator
Aviator

Reputation: 722

How to declare array in shell script?

I am trying to declare an array in my shell script and then have written a for loop to access those array elements into another file. But it is only taking the first element. I've tried the below :

raw_cd=(1150 1151)
i=0


for i in "${raw_cd[@]}"
do
  grep -wr  "${raw_cd[@]}" file1.txt  > /opt/tmp/raw.txt
  echo "$i"
done

It is taking only the first element 1150 and also giving output as :-

file1.txt:|1150|
file1.txt:|1150|
file1.txt:|1150|

where am i doing wrong?

Upvotes: 1

Views: 2606

Answers (1)

Amadan
Amadan

Reputation: 198314

for does not deal with indices, just raw values. Thus,

raw_cd=(1150 1151)
for i in "${raw_cd[@]}"
do
  echo "$i"
done

will print

1150
1151

If you want to use indices, you need to produce them yourself:

raw_cd=(1150 1151)
for i in $(seq "${#raw_cd[@]}")
do
  echo "$i": "${raw_cd[$i - 1]}"
done

will produce

1: 1150
2: 1151

Even better, you can directly get keys like this, without seq (this will work even on associative arrays):

raw_cd=(1150 1151)
for i in "${!raw_cd[@]}"
do
  echo "$i": "${raw_cd[$i]}"
done

Upvotes: 2

Related Questions