justin8976
justin8976

Reputation: 67

bash: print a dynamic variable using dynamic name

In a for, I have the following:

COUNT="1"  
GEOZONE[1]="EU"  
declare -A CLIENTS_"${GEOZONE[$COUNT]}"="client1 client2"

At this point, if I would like to print ${CLIENTS_EU} it works, but how to print that by using the GEOZONE array?

I got bad substitution while trying to:

~ $ echo ${CLIENTS_${GEOZONE[$COUNT]}}
bash: ${CLIENTS_${GEOZONE[$COUNT]}}: bad substitution

And I got EU while trying to:

~ $ echo $CLIENTS_${GEOZONE[$COUNT]}
EU

I would like to get client1 client2

Thanks

Upvotes: 1

Views: 62

Answers (1)

anubhava
anubhava

Reputation: 785058

You need to create a separate variable that will hold composite variable name:

# ccomposte variable name
var=CLIENTS_"${GEOZONE[$COUNT]}"

# assign value
declare $var="client1 client2"

# print it
echo "${!var}"

client1 client2

Upvotes: 1

Related Questions