Linux shell编程学习笔记34:eval 命令

0 前言

在JavaScript语言中,有一个很特别的函数eval,eval函数可以将字符串当做 JavaScript 代码执行,返回表达式或值。

在Linux Shell 中也提供了内建命令eval,它是否具有JavaScript语言中eval函数的功能呢?

1 eval命令的格式、功能和返回值

我们可以使用 help eval命令来查看eval命令的帮助信息。

purpleEndurer @ bash ~ $ ++help eval++

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.

1.1 eval命令的格式

eval 参数...

参数说明:参数不限数目,彼此之间用分号分开。

1.2 eval 命令的功能

将参数作为 shell 命令执行。

确切来说,是将参数组合成一个字符串,将结果用作 shell 的输入,并执行生成的命令。

1.3 eval命令的返回值

  • 如果没有参数,eval返回成功(0)。
  • 如果有参数,eval返回参数作为命令执行后的退出状态。

2 eval 命令用法实例

2.1 eval不带参数

purpleEndurer @ bash ~ $ ++eval++

purpleEndurer @ bash ~ ++echo ?++

0

2.2 eval简单回显

purpleEndurer @ bash ~ ++echo 0++

bash

purpleEndurer @ bash ~ ++eval echo 0++

bash

可见 命令 ++eval echo 0++ 和 ++echo 0++ 的功能是一样的。

2.3 利用eval命令执行其它命令

我们把命令 echo hello 赋值给变量c,再用eval命令来这个命令:

purpleEndurer @ bash ~ $ ++c="echo hello"++

purpleEndurer @ bash ~ ++eval c++

hello

2.4 利用eval命令执行函数

我们先定义3个函数a1、a2、a3

bash 复制代码
function a1()
{
	echo a1; #显示 a1
}

function a2()
{
	echo a2; #显示 a2
}

function a3()
{
	echo a3; #显示 a3
}

2.4.1 用for循环调用eval命令来执行它们

purpleEndurer @ bash ~ $ ++function a1(){ echo a1; }; function a2(){ echo a2; }; function a3(){ echo a3; }++

purpleEndurer @ bash ~ ++for i in {1..3}; do eval a{i}; done++

a1

a2

a3

purpleEndurer @ bash ~ $

2.4.2 根据用户输入的数字执行相应的函数

purpleEndurer @ bash ~ $ ++function a1(){ echo a1; }; function a2(){ echo a2; }; function a3(){ echo a3; }++

purpleEndurer @ bash ~ ++echo -n enter 1 or 2 or 3:; read i; eval a{i}++

enter 1 or 2 or 3:1

a1

purpleEndurer @ bash ~ ++echo -n enter 1 or 2 or 3:; read i; eval a{i}++

enter 1 or 2 or 3:3

a3

purpleEndurer @ bash ~ ++echo -n enter 1 or 2 or 3:; read i; eval a{i}++

enter 1 or 2 or 3:4

bash: a4: command not found

purpleEndurer @ bash ~ $

只要我们输入1或2或3,就可以相应地执行a1、a2或a3,输入其它数字则出错。

2.5 在脚本中获取最后一个命令行参数

我们先用cp /dev/stdin a.sh命令创建脚本a.sh,内容如下:

bash 复制代码
echo "\$$#"         
eval echo "\$$#"

purpleEndurer @ bash ~ $ ++cp /dev/stdin a.sh++

echo "\$$#"

eval echo "\$$#"

purpleEndurer @ bash ~ $ ++. a.sh 1 2 3++

$3

3

purpleEndurer @ bash ~ $

我们直接使用命令echo "\$$#",显示出来的是 $3

我们使用eval echo "\$$#",将最后一个参数3正确显示出来了。

相关推荐
tangwangbi1 小时前
Linux 系统配置文件:/etc/profile、~/.bashrc 和 ~/.bash_profile 三者之间的区别与作用
linux·运维·bash
蜀道山老天师2 小时前
Shell Bash变量与运算符(含条件测试与流程控制)
linux·运维·bash
Mr.朱鹏2 小时前
Linux 服务器 LVM 根分区在线动态扩容
linux·服务器·数据库
mengge.cloud2 小时前
存储技术基础小白教程
linux·运维·服务器·wpf·存储
tang777893 小时前
反爬虫场景下代理IP池的动态扩容与失效IP自动清理方案实现
linux·服务器·网络·爬虫代理·住宅代理ip
新时代牛马4 小时前
Linux 系统调用与IPC 完整篇:从syscall 入口、VDSO 到pipe/shm/futex 选型
linux·运维·服务器
软件开发技术深度爱好者5 小时前
动态数学软件GeoGebra的使用
学习笔记·数学广角·科普向未来
fpcc5 小时前
计算机原理—Linux是如何加载可执行文件到内存
linux
野熊佩骑5 小时前
Kubernetes实战系列文章(三) 之 K8S运维常用命令
linux·运维·docker·微服务·云原生·容器·kubernetes
码农客栈5 小时前
linux 设备树下的 platform 驱动编写
linux