how to use array variables in shell

Hi, everyone.

I wrote a code like this

for f in HB021*
  do 
   program
done

for f in HB034*
   do 
     program
done

for f in HB056*
    do 
       program
done
.
.
.
.
.
.

I know that a loop with array variables is much easier to do this. I searched online, but I can't achieve it.

vari[0]=021
vari[1]=034
vari[2]=056

How can I use this array variable in the filename?

Thanks in advance!

This thread might help.

#!/bin/bash

num[0]=021
num[1]=034
num[2]=056

for ((i=1;i<=5;i++))
 do
    for f in HB*
      do
         if [[$f == HB${num*}]]; then
            echo $f
         else
           break
         fi
       done

done

Could you please help to check this code?

Try this instead-

#!/bin/bash

declare -a num
num=( 021 034 056 )

for ((i=0;i<=2;i++))
do
    for f in HB*
      do
         fname="HB${num}"
         if [[ "$f" == "$fname" ]]; then
            echo $f
         else
           break
         fi
       done
done
#!/bin/bash

declare -a num
num=( 086 088 143 291 292)

for ((i=1;i<=4;i++))
 do
    for f in HB*
      do
         fname="HB${num}*"
         if [[ "$f" == "$fname" ]]; then
            echo $f
         else
           echo "wrong"
         fi
       done

done

I need a * after HB${num[i]}, cause the file names are like this "HB086-AA-A8.txt"

but

fname="HB${num}*"

seems wrong.

---------- Post updated at 07:15 PM ---------- Previous update was at 12:09 AM ----------

#!/bin/bash

declare -a num
num=( 086 088 143 291 292)

for ((i=1;i<=4;i++))
 do
    for f in HB*
      do
         fname="HB${num}"
         if [[ "$f" == "$fname"* ]]; then
            echo $f
         else
           echo "wrong"
         fi
       done

done

We're talking bash now. Assigning the array either way is fine; num=( 086 088 143 291 292) may be a bit more efficient. The ${...} construct will allow you to access the array's features and members:

echo ${#num[@]}, ${num[@]}
5, 086 088 143 291 292

#: element count; @: all elements; 0 .. 4 individual element.
In order to access individual files in a directory, you need to decollate the patterns, like e.g.

for f in ${num[@]}
   do for g in HB$f*
      do ls $g
         done
     done 
HB086
HB0861
HB0862
HB0863
HB088
HB0881
HB0882
HB0883
HB143
HB1431
... 

f will run through all elements of the num array, while g will address every single file in that particular directory who's name is starting with "HB", having one of the num elements as part of its name, and then any postfix existing that dir ("", 1, 2, 3 in this example).

You could of course run the numerical for loop like

for ((i=1;i<${#num[@]};i++))

to make sure you are addressing every single element of num.

1 Like