3

I think this is a rather simple question but, I cant make this work: I have a whole lists of variables eg:

SP60=OLA SP61=BYE SP62=TRT

I want to create a loop to call them in the specific number of the variable so I thought a short solution could be:

for i in {60..62}; do SP=$"SP$i"; echo $SP.txt; done

I was expecting the outcome to be:

OLA.txt BYE.txt TRT.txt

but I get

SP60.txt...

I would like to know if there is a simple way to get this done.

Mat
  • 52,586

2 Answers2

4

Consider the following bash/ksh script:

SP60="OLA"
SP61="BYE"
SP62="TRT"

for (( i = 60; i <= 62; ++i )); do
    typeset -n var="SP$i"
    printf 'SP%d = %s.txt\n' "$i" "$var"
done

It will output the following:

SP60 = OLA.txt
SP61 = BYE.txt
SP62 = TRT.txt

It uses a name reference variable var (declared using declare -n in bash or with typeset -n in both bash and ksh). It means that every time you dereference it, it will expand to the value of the variable that it's referencing.

Kusalananda
  • 333,661
2

Another option once the variables are already initialized:

for i in $SP{60..62}; do echo $i.txt; done