Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I need to create dynamically a variable name as follows (simplified example):

#!/bin/sh

IDX=1
SERIES1="a b c d e f g"
SERIES2="h i j k l m n"

# How to get this value contains $SERIES1 or $SERIES2
# depending on the value of $IDX
CURRENT=${SERIES\${IDX}} # doesn't work, just an example

If IDX=1 I'd expect to have

echo $CURRENT

to display

a b c d e f g

and if IDX=2 to display

h i j k l m n

I will need to use it in a loop for an undetermined number of SERIES coming from another script.

EDIT Currently using sh as shell but if needed I can use a different one (even if it means I might need to convert a few things but it's ok)

My question is: How do I assign the desired series to CURRENT

What have I tried? The example above (that doesn't work) and other flavors like:

CURRENT=$${SERIES$${IDX}}
CURRENT=${SERIES${IDX}}

EDIT2

I am on the way to something:

eval echo $`echo "SERIES$IDX"`

This displays the correct series. However I can't find a way to assign it to CURRENT:

CURRENT=eval echo $`echo "SERIES$IDX"`

But I guess more digging and I'll find something. Any help appreciated though

EDIT3

Ok I found it:

eval "CURRENT=\$SERIES$IDX"
echo $CURRENT

display what I expect, so CURRENT has the right content.

share|improve this question

2 Answers 2

Thanks to this website (and probably others have similar answer...):

#!/bin/sh

IDX=1
SERIES1="a b c d e f g"
SERIES2="h i j k l m n"

eval "CURRENT=\$SERIES$IDX"

Now CURRENT holds the content of SERIES1. If I change IDX to 2 then I get SERIES2 content.

share|improve this answer

This isn't precisely what you want, but if you use bash instead of sh then you can use arrays:

IDX=1
SERIES[1]="a b c d e f g"
SERIES[2]="h i j k l m n"

CURRENT=${SERIES[$IDX]}
share|improve this answer
    
Thank you. I'd take it as last option but I found a way in sh –  JScoobyCed May 22 '13 at 9:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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