shell 的 eval 命令用法

文章详细解释了eval命令的作用,即接收参数并作为shell命令执行。通过实例展示了如何利用eval执行自定义脚本,并介绍了$#和$@变量在参数处理中的应用。
摘要由CSDN通过智能技术生成

在看一些应用自带的脚本时,经常看到 ‘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]#

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值