0

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
0

3 Answers 3

1

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.

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

1 Comment

Well, if you do end up using this method instead please mark this as the correct answer. Other than that, glad to help :)
0

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.

Comments

0

You can use eval

eval echo \$ANIMAL$i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.