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.

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.