Hi Guys,
I was scratching my head for this for half a day... finally not successful
Following is the problem
I have a variable
$ var1=123
$ var2-234
$ var3=345
and another Variable
$ i=1
Now i wanted to save these into a Variable as shown below
for i in 1 2 3
do
con=${var$i)
echo $con
done
Was kicked by saying
ksh: con=${var$i}: 0403-011 The specified substitution is not valid for this command.
my goal is the variable con should contain the values, when con is echoed (i.e 123,234 & 345)
Pls help ...
The shell thinks you're performing a parameter expansion.
Try this:
con=var$i
1 Like
You can't directly expand a variable with a variable name. Here is a Korn shell script that provides four ways to do what you seem to be trying to do. Note that if the values you're assigning to var1, var2, or var3 are supplied by a user (or an untrusted external source of any kind), using eval can be dangerous:
#!/bin/ksh
var1=123
var2=234
var3=345
for i in 1 2 3
do eval con=\${var$i}
echo "$con (using eval)"
done
echo
var=(ignored 123 234 345)
for i in 1 2 3
do con=${var[$i]}
echo "$con (using ksh array w/subscript 1-3)"
done
echo
var=(123 234 345)
for i in 0 1 2
do con=${var[$i]}
echo "$con (using ksh array w/subscript 0-2)"
done
echo
for con in 123 234 345
do echo "$con (using for loop directly)"
done
This script produces the output:
123 (using eval)
234 (using eval)
345 (using eval)
123 (using ksh array w/subscript 1-3)
234 (using ksh array w/subscript 1-3)
345 (using ksh array w/subscript 1-3)
123 (using ksh array w/subscript 0-2)
234 (using ksh array w/subscript 0-2)
345 (using ksh array w/subscript 0-2)
123 (using for loop directly)
234 (using for loop directly)
345 (using for loop directly)
1 Like
eval runs the evaluation twice
eval con=\$var$i
After the first evaluation this becomes e.g.
con=$var1
1 Like
Why are you trying to do this? Dynamic variable names are generally a terrible idea, and the usual things people want them for are often easily solved by other methods.
1 Like
@in2nix4life: Thanks for your suggestion...:), but when tried it out and echo con the result what i got is as below
$ echo $con
var1
@Don Cragun, MadeInGermany: It worked perfectly... Thanks a lot...
@Corona688: This is just an idea which i got at that moment... I dont have any specific reason for this... Kindly let me know the other methods to achieve this...