4

I tried below shell code to get the value of temp as "good 1" and "good 2", but I was not able to.

hello_1="good 1"
hello_2="good 2"
for i in 1 2
do
temp="hello_$i"
echo $temp
done

I want to fetch hello_1 and hello_2 variables value into temp variable. I tried above script but I was not able to get values of hello_1 and hello_2 into temp. please help me.

1
  • May be try to concat like ${hello_${i}}. Try and let us know whether working or not. Also try to echo value Commented Dec 29, 2014 at 3:43

1 Answer 1

4

If you using bash 4 or higher, read about indirect references. But to answer your question you can do

hello_1="good 1"
hello_2="good 2"
for i in 1 2
do
    eval temp="\$hello_$i"
    echo $temp
done

output

good 1
good 2

eval is usually considered evil in shell programming. Don't get in a habit of using it.

The key technique is that the eval provides a 2nd evaluation of the line. On the first pass it looks like

 eval temp="$hello_1"

Note how the $i is displayed as 1, AND that the leading \\ char is removed from \$hello_1, so when the eval is executed the processing of the line takes the value of $hello_1 variable and assigns it to temp, i.e.

 temp="good 1"

IHTH

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

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.