在看一些应用自带的脚本时,经常看到 ‘eval’ 这个命令,但是我不知道,这个命令是什么意思。经过搜索及实践,了解了这个 ‘eval’ 命令的 用法。
[root@master scripts]# eval --help
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
[root@master scripts]#
从 eval --help 的返回看,意思就是:将参数当作一个 shell 命令 执行。
后面又继续作了说明:把参数结合起来当作一个单一的字符串,然后将这个字符串作为 shell 命令 执行之
下面举例用具体的例子说明
[root@master scripts]#
[root@master scripts]# cat mytest.sh
#!/bin/bash
echo $1
echo $0
echo $@
echo $#
eval echo \$$#
[root@master scripts]#
[root@master scripts]# name="cat mytest.sh"
[root@master scripts]#
[root@master scripts]# eval $name
#!/bin/bash
echo $1
echo $0
echo $@
echo $#
eval echo \$$#
[root@master scripts]#
在上面的例子中,参数就是 $name,它的值呢就是 “cat mytest.sh” , eval $name 命令就相当于 是 执行 cat mytest.sh
再看一个例子
[root@master scripts]#
[root@master scripts]# /bin/bash mytest.sh 1 2 3
1
mytest.sh
1 2 3
3
3
[root@master scripts]#
[root@master scripts]# /bin/bash mytest.sh 1 2 8
1
mytest.sh
1 2 8
3
8
[root@master scripts]#
[root@master scripts]# cat mytest.sh
#!/bin/bash
echo $1
echo $0
echo $@
echo $#
## $# 这个变量的意思 是 参数的数量,在上面两个例子里面,$#=3, 下面的命令就是打印 第3个参数的值
eval echo \$$#
[root@master scripts]#