Reputation: 45
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.
Upvotes: 4
Views: 8609
Reputation: 37318
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
Upvotes: 4