1

I have below bash script

declare -a input=('alpha'  'beta'  'gama');
alpha="cow"
beta="goat"
gama="crow"
for i in "${input[@]}"
do
   echo $(eval "echo $i") [this is wrong logic]
done

I want that when i iterates over the array it shall print cow,goat crow instead of alpha,beta and gama. How can i evaluate this some thing like $($i) where $i when evaluates to alpha,it sees it as $alpha and evaluates the same to cow.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
thinkingmonster
  • 5,063
  • 8
  • 35
  • 57

2 Answers2

5

You can use parameter expansion:

echo ${!i}

Quoting from the manual:

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
0

Use an associative array (bash v4.3)

declare -A input=( 
    [alpha]=cow 
    [beta]=goat 
    [gamma]=crow 
)

for key in "${!input[@]}"; do 
    echo "$key -> ${input[$key]}"
done
gamma -> crow
alpha -> cow
beta -> goat

Associative arrays don't maintain order of the keys. If that's important, you can keep a separate list of keys:

declare -a keys=( alpha beta gamma )
for key in "${keys[@]}"; do echo "$key -> ${input[$key]}"; done
alpha -> cow
beta -> goat
gamma -> crow
glenn jackman
  • 238,783
  • 38
  • 220
  • 352