eval用来在执行命令时作二次解析:主要是每次执行一个shell命令它会先检察一次,看到有$标志就会把值替换一次,然后再执行一遍。eval不会唤起起另一个shell来执行,而是在本身这个shell内多解析一次,所以替换的结果可以保留下来使用。
官方说明:
使用模式:eval [argument …]
功能描述:通过将给定的参数以一个空格为分隔符连接在一起构造出一条命令。构造出的命令会被 shell 读取并执行。
退出状态:如果没有参数,或者只有 null 参数,eval 将会返回退出状态(exit status)0;否则,它会返回 构造出的命令的 退出状态。
官方示例:
It will take an argument and construct a command of it, which will be executed by the shell. This is the example of the manpage:
In the first line you define
$foowith the value'10'and$xwith the value'foo'.Now define
$y, which consists of the string'$foo'. The dollar sign must be escaped with'$'.To check the result,
echo $y.The result will be the string
'$foo'Now we repeat the assignment with
eval. It will first evaluate$xto the string'foo'. Now we have the statementy=$foowhich will get evaluated toy=10.The result of
echo $yis now the value'10'.
使用示例:
#!/bin/bash
# eval.sh:example for eval
pages=4
#for ((i=1; i<=${pages}; i++))
for i in $(eval echo {1..${pages}})
do
echo $i
done
printf "%0.s-" {1..20}
#printf '%0.s-' $(seq 1 $variable)
echo
count=1
var1=I
var2=am
var3=a
var4=script
while [ $count -lt 5 ]; do
eval "echo \$var$count"
let 'count=count + 1'
done
# 输出结果:
1
2
3
4
--------------------
I
am
a
scriptcount会一直变化1 2 3...,同时替换var1 var2 var3,然后再对var1 var2 var3...取值。其中因为第一个var不想被运算,所以先用\构造一个变量, 然后第二次运算时才会被替换解析。当然如果要三次以上变量替换在一行内解析也是可行的。
$ eval ". foo.sh",eval还可以用来调用执行另一个shell脚本,脚本在同一个shell下执行,因此变量在此shell内都是有效的。
参考: