eval的疑问!

eval的疑问!

[dell@scsm dell]$ unamer=`uname -r`
[dell@scsm dell]$ eval version=`echo $unamer | awk -F '.' '{ print "(" $1 " " $2 ")" }'`
[dell@scsm dell]$ echo $version
2
[dell@scsm dell]$ version=`echo $unamer | awk -F '.' '{ print "(" $1 " " $2 ")" }'`
[dell@scsm dell]$ echo $version
(2 4)
[dell@scsm dell]$ version="(2 4)"
[dell@scsm dell]$ echo $version
(2 4)
[dell@scsm dell]$ eval version="(2 4)"
[dell@scsm dell]$ echo $version
2
为什么加入eval后version值发生了变化,eval起到什么作用?      
version="(2 4)" 是将字符串赋值给 version; eval version="(2 4)" 执行时变成了 version=(2 4), 是把数组 (2 4) 赋值给 version:
引用:
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[16167 0] ; eval v="(2 4)"
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[16167 0] ; echo ${v[0]}
2
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[16167 0] ; echo ${v[1]}
4
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[16167 0] ; echo ${v[@]}
2 4
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[16167 0] ; bye
eval 的功能是将其参数作为输入传给当前的 shell      
常见的 scripting languages (如 perl, python, tcl, php) 都有提供一个 eval 函数/指令, 用以动态构造并执行语句, 这也是 scripting languages 区别于 C/C++ 之类语言的一大特点/优点       
明白了!Thank You Very Much!      
dearvoid能举出一些eval的例子吗?      
FYI:
引用:
-(dearvoid@LinuxEden:Forum)-(~/void/bash)-
[30470 0] ; cat random.sh
#! /bin/bash

cmd="hexdump -e '\"%02x\" \"\\n\"' -n 4 /dev/random"
echo "\$ $cmd"
eval $cmd

cmd="echo \$RANDOM"
echo "\$ $cmd"
eval $cmd
-(dearvoid@LinuxEden:Forum)-(~/void/bash)-
[30470 0] ; ./random.sh
$ hexdump -e '"%02x" "\n"' -n 4 /dev/random
43dccb1f
$ echo $RANDOM
5486
-(dearvoid@LinuxEden:Forum)-(~/void/bash)-
[30470 0] ; bye
      
FYI:
引用:
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[21645 0] ; cat foo.sh
#!/bin/sh

eval "v=\$(( $@ ))"
echo "$@ = $v"
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[21645 0] ; ./foo.sh 1 + 2
1 + 2 = 3
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[21645 0] ; ./foo.sh 3 '**' 3
3 ** 3 = 27
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[21645 0] ; ./foo.sh 7 '*' 11 '*' 13
7 * 11 * 13 = 1001
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[21645 0] ; bye
      
非常感谢!回去仔细研究研究!      
前几天 jiahuan 发的把 ASCII 码转成 char 的例子也可以借鉴一下:
引用:
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[30505 0] ; cat ascii2chr.sh
#!/bin/bash

ascii2chr()
{
    printf -v ascii '%x' $1
    eval echo -e "'\\x$ascii'"
}

for i in 97 98 99; do
    ascii2chr $i
done
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[30505 0] ; ./ascii2chr.sh
a
b
c
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[30505 0] ; bye
      
例子非常的好!!!