shell eval命令学习

1 eval描述

《POSIX编程手册》上介绍eval的原文为:

construct command by concatenating arguments
The eval utility shall construct a command by concatenating arguments together, separating each with a <space>. 
The constructed command shall be read and executed by the shell.

eval命令将会首先扫描命令行进行所有的替换,类似于C语言中的宏替换,然后再执行命令。该命令使用于那些一次扫描无法实现其功能的变量。该命令对变量进行两次扫描。这些需要进行两次扫描的变量有时候被称为复杂变量。

2 关键用途

2.1 执行含有字符串的命令

#### 1 eval也能用来执行含有字符串的命令
eval $(echo "$file1")
eval $file1
================下面为准备条件
[root@centos ~]# cat 1.log
sdfasdf sdf
sdfasfasdfasdf
sadfasdf
[root@centos ~]# file1="cat 1.log"
[root@centos ~]# echo $file1
cat 1.log
[root@centos ~]# eval $(echo $file1)
sdfasdf sdf
sdfasfasdfasdf
sadfasdf
[root@centos ~]# eval $file1
sdfasdf sdf
sdfasfasdfasdf
sadfasdf

image-20220628223408535

2.2 传递脚本最后一个参数

[root@centos 01-test]# cat test.sh
#!/bin/bash
eval echo \$$#
[root@centos 01-test]# sh test.sh 1 2 4 5 7
7

######### 下面是一个对比效果

[root@centos 01-test]# cat test.sh
#!/bin/bash
echo "01 test echo, below:"
echo \$$#
echo "02 test eval, below:"
eval echo \$$#
[root@centos 01-test]# sh test.sh 1 2 4 5 7
01 test echo, below:
$5
02 test eval, below:
7

2.3 作为指针

[root@centos 01-test]# val1=100
[root@centos 01-test]# ptr1=val1
[root@centos 01-test]# eval echo \$$ptr1
100
[root@centos 01-test]# eval $ptr1=50
[root@centos 01-test]# echo $val1
50

2.4 简单变量回显

[root@centos 01-test]# val=100
[root@centos 01-test]# echo $val
100
[root@centos 01-test]# eval echo $val
100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值