Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a shell variable to choose one bash array

I am trying to write a bash script to allow me to choose one array amongst a set of different arrays. For that purpose, I intend so use a simple variable to reference that one array.

#!/bin/bash
#To get all the members of a given array as the output
#variables
FIRST=(A B C D)
SECOND=(planes cars trains bicycles gocarts)
THIRD=(werewolfs vampires zombies ghosts daemons)
FOURTH=(football soccer basketball rugby batmington zumo)
FIFTH=(handguns rifles machineguns bazookas slingshots)
SIXTH=(dogs cats turtles ferrets birds hamsters fish)
SEVENTH=(monday tuesday wednesday thursday friday saturday sunday)

#execution
select ARRAY in "FIRST" "SECOND" "THIRD" "FOURTH" "FIFTH" "SIXTH" "SEVENTH"; do 
    OUTPUT=eval '"${'${ARRAY}'[@]}"'
    echo $OUTPUT
    break 
done

#end

The above script does not work. So far, I have tried to replace line 9 with these options:

OUTPUT=eval '$'{ARRAY'[@]'}
OUTPUT=eval ${"$ARRAY"[@]}
OUTPUT=eval ${'$ARRAY'[@]}
OUTPUT=eval ${'$'ARRAY[@]}
OUTPUT=eval '$'{"$ARRAY"[@]}
OUTPUT=eval \${${ARRAY}[@]}

What am I missing here?

like image 961
user148854 Avatar asked Nov 19 '25 13:11

user148854


1 Answers

This worked for me:

#!/bin/bash
#To get all the members of a given array as the output
#variables
FIRST=(A B C D)
SECOND=(planes cars trains bicycles gocarts)
THIRD=(werewolfs vampires zombies ghosts daemons)
FOURTH=(football soccer basketball rugby batmington zumo)
FIFTH=(handguns rifles machineguns bazookas slingshots)
SIXTH=(dogs cats turtles ferrets birds hamsters fish)
SEVENTH=(monday tuesday wednesday thursday friday saturday sunday)

#execution
ARRAY="FIFTH"
select ARRAY in "FIRST" "SECOND" "THIRD" "FOURTH" "FIFTH" "SIXTH" "SEVENTH"; do
    eval "OUTPUT=\${$ARRAY[*]}"
    echo $OUTPUT
    break
done

eval can be used to introduce new variables. We construct a string that contains the expression assigning the desired value to OUTPUT and then eval it, thus introducing a new variable OUTPUT with the desired value.

like image 136
nicebyte Avatar answered Nov 22 '25 04:11

nicebyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!