Chan Kim
Chan Kim

Reputation: 5919

using variable to make variable name in shell script

I want to echo $ANMIAL0 and then $ANIMAL1 using a script below. But I get line 7: ${ANIMAL$i}: bad substitution error message. What's wrong?

#!/bin/sh
ANIMAL0="tiger"
ANIMAL1="lion"
i=0
while test $i -lt 2; do
echo "Hey $i !"
echo ${ANIMAL$i}
i=`expr $i + 1`
done

Upvotes: 0

Views: 47

Answers (3)

Semirix
Semirix

Reputation: 281

You're probably better off using an array instead of ANIMAL0 and ANIMAL1. Something like this maybe?

#!/bin/bash

animals=("Tiger" "Lion")

for animal in ${animals[*]}
do
    printf "Hey, ${animal} \n"
done

Using eval will get you into trouble down the road and is not best practice for what you're trying to do.

Upvotes: 1

tripleee
tripleee

Reputation: 189317

The problem is that the shell normally performs a single substitution pass. You can force a second pass with eval, but this obviously comes with the usual security caveats (don't evaluate unchecked user input, etc).

eval echo \$ANIMAL$i

Bash has various constructs to help avoid eval.

Upvotes: 0

Kalanidhi
Kalanidhi

Reputation: 5092

You can use eval

eval echo \$ANIMAL$i

Upvotes: 0

Related Questions