0

please take look on the following commands down, ( the shell is sh )

something not clearly for me

when I run - eval echo \$arr$n , I get the value a as expected

so why: VAL=` eval echo \$arr$n ` , and echo $VAL not print the same value a ?

set a value in arr1

# n=1
# eval arr$n=a

print a value from arr1

# n=1
# eval echo \$arr$n
  a

set eval echo \$arr$n in to VAL , and print $VAL

# VAL=` eval echo \$arr$n `
# echo $VAL
{*}1

what need to fix in the command - VAL=` eval echo \$arr$n ` , so when I do echo $VAL I will get the value a ?

ams
  • 24,923
  • 4
  • 54
  • 75
maihabunash
  • 1,632
  • 9
  • 34
  • 60
  • 2
    Judging from the use of `#` as a shell prompt, you're running as `root`. Don't test code as `root`; it is dangerous. I've only been using Unix for over thirty years, and I don't do anything as `root` unless it is absolutely necessary. It's safer, by a large margin. – Jonathan Leffler Jul 03 '14 at 15:33
  • Hi dont worry this is test machine , so we can do anything on that machine -:) – maihabunash Jul 03 '14 at 15:37
  • 1
    Regardless of whether it's a test machine, it's a bad habit to get into. Get used to sudo when you really need root access; for tests like this, you simply don't need it. – Palpatim Jul 03 '14 at 15:45
  • Beware of eval! If the variable you are eval'ing can be manipulated into containing a command, eval will run it! see here for more info: http://stackoverflow.com/questions/17529220/why-should-eval-be-avoided-in-bash-and-what-should-i-use-instead – Gary_W Jul 03 '14 at 20:48

1 Answers1

0

Testing with Bash 3.2 (on Mac OS X 10.9.4) run as sh:

sh-3.2$ n=1
sh-3.2$ eval arr$n=a
sh-3.2$ eval echo \$arr$n
a
sh-3.2$ VAL=`eval echo \$arr$n`
sh-3.2$ echo $VAL
1
sh-3.2$ VAL=$(eval echo \$arr$n)
sh-3.2$ echo $VAL
a
sh-3.2$ VAL=`eval echo \$arr$n`
sh-3.2$ echo $VAL
1
sh-3.2$ VAL=`eval echo \\$arr$n`
sh-3.2$ echo $VAL
a
sh-3.2$ arr=xyz
sh-3.2$ VAL=`eval echo \$arr$n`
sh-3.2$ echo $VAL
xyz1
sh-3.2$ 

Note that there is a difference between using back-ticks and $(…). I recommend the use of $(…) because it is simpler to understand. If you want to stick with back-ticks, double up the back-slashes. (I'm not quite sure why it is behaving as it is, but that's what the empirical evidence says you need to do.)

If you want to use arrays, use arrays:

arr=('' a)
echo "${arr[1]}"
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278