Bash eval命令及其常见用法
2016-03-30 13:42
381 查看
POSIX的解释:
eval - construct command by concatenating arguments
先感受下面的几行命令:
可以看出,最后两次的n被当成变量解析了。
下面讲一个小程序:
执行结果:
参考文章:
What is the “eval” command in bash?
eval command in Bash and its typical uses
eval - construct command by concatenating arguments
先感受下面的几行命令:
[root@localhost shell]# set -- one two three # 设置 $1 $2 $3 [root@localhost shell]# echo $1 one [root@localhost shell]# n=1 [root@localhost shell]# echo ${$n} ## 第一次尝试用大括号 bash: ${$n}: bad substitution [root@localhost shell]# echo $($n) ## 第二次尝试用小括号 bash: 1: command not found [root@localhost shell]# echo ${!n} ## 第三次尝试用!解析 one [root@localhost shell]# eval echo \${$n} one [root@localhost shell]#
可以看出,最后两次的n被当成变量解析了。
${$n}是语法错误。在大括号中只能出现带前缀或后缀的变量名。这时可以用下面的方式:
echo ${!n}
$(...)这个命令将小括号内的命令在新的进程中执行,即继承了当前shell变量和设置的子shell,并接收它的输出。所以
$($n)把
$n当作一个shell命令。
eval echo \${$n}把参数传给
eval。
下面讲一个小程序:
#!/bin/bash count=$# # 参数个数 cmd=echo while [ $count -gt 0 ] do cmd="$cmd \$$count" # cmd后接 $count count=`expr $count - 1` # $count减1 done eval $cmd # 解析 $cmd 并执行
执行结果:
[root@localhost shell]# bash eval.sh hello world to bash shell shell bash to world hello
参考文章:
What is the “eval” command in bash?
eval command in Bash and its typical uses
相关文章推荐
- shell队列实现线程并发控制
- Linux shell脚本学习和实战之一
- 简易Shell
- linux 命令快捷键(xshell环境下)
- ZSC 1316 取石子 (nimm + bash)
- spark-shell无法退格/删除
- linux64位shellcode代码注入
- seq 工具介绍
- /etc/profile、~/.bash_profile等几个文件的执行过程
- Shell特殊变量:$*和$@的区别
- SHELL中时间的比较
- 递归遍历目录的shell脚本
- 硬盘故障时无法关机:bash: /sbin/shutdown: Input/output error
- 王晓博 2010.12.22-3-模拟linux shell 终端环境 执行所有shell命令
- Linux bashrc和profile的用途和区别
- shell游戏:扫雷
- 程冬冬 2010.04.28 shell
- Unix Shell 介绍
- shell 编程例子—第9章源码
- XSHELL 绝佳配色方案, 保护你的眼睛