Jericon
Jericon

Reputation: 5172

Double Interpolation of Array in Bash

I'm trying to make a script so that I can easily add host types to it without changing the code itself. Each type of host has a specific group of id's and templates associated with it. Here is the cod that I have derived:

CLASS="memcache"
memcache_template=( 42 45 )
CLASS_template=${CLASS}_template
template=$( eval echo $`echo $CLASS_template` )

for i in  ${template[@]}; do
  echo $i
done

The output that I get is just "42". I need it to output both 42 and 45.

Upvotes: 2

Views: 871

Answers (1)

Michael Hoffman
Michael Hoffman

Reputation: 34324

Here's a way to do it:

CLASS="memcache"
memcache_template=(42 45)

CLASS_template=${CLASS}_template[@]

for i in ${!CLASS_template}; do
  echo $i
done

See the discussion of variable indirection in info "(bash)Shell Parameter Expansion". Note that you cannot use ${!CLASS_template[@]} because that has a special meaning. The array subscripting must be done before indirection.

Upvotes: 3

Related Questions