3

This question already has an answer here:

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.

marked as duplicate by don_crissti, countermode, GAD3R, Archemar, Eric Renouf Jan 13 '17 at 13:58

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

Another option once the variables are already initialized:

for i in $SP{60..62}; do echo $i.txt; done
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.