Search code examples
bashshellvariablesexpansion

An issue with variable expansion. Get a variable into the name of the variable to echo


I'd really appreciate help with this. I have 3 strings and I want to echo one of them randomly.

INTRO0="Welcome to Foo"
INTRO1="Foo welcomes you"
INTRO2="We are glad to see you at Foo"

R=$((RANDOM%3))

echo $INTRO${R}

I expect it to expand the value of R so it'll interpret it as e.g. echo $INTRO1

I've made it work with if statements where it checks the value of R and prints the appropriate INTRO, but if I had 10 strings it would get messy with if statements. Is it possible to do it this way?

Thanks


Solution

  • For bash:

    intro_r=INTRO$R
    echo ${!intro_r}
    

    But I would use a single array intro instead of three individual variables INTRO1 and so on:

    intro=( "..." "..." "..." )
    echo ${intro[$R]}