0

I have the following script:

var1="var1value"
var2="var2value"
var3="var3value"

I want to create the following code:

option=$1

myvar=`echo var$option`

So, when the option is "1" the myvar should be var1value, when the option is "2" the myvar should be "var2value" etc.

How can I do that?

1 Answer 1

0

This will do what you want:

myvar=$(eval echo \$var$option)

However, eval is a risky instruction so you'd rather use an array instead of this kind of variable naming, eg:

var[1]="var1value"
var[2]="var2value"
var[3]="var3value"

option=$1

myvar=${var[$option]}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .