LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1292|回复: 3

{}操作符里面的!号是什么意思??

[复制链接]
发表于 2008-5-9 17:01:39 | 显示全部楼层 |阅读模式
#! /bin/bash

args=$# # 位置参数的个数
lastarg=${!args}

上面是我在学习shell编程时候看到的代码,我不明白为什么不直接用args,还要在前面放一个 !号,大家能帮我解释下吗??
发表于 2008-5-26 18:19:36 | 显示全部楼层
Post by azhenfeixue;1847623
#! /bin/bash

args=$# # 位置参数的个数
lastarg=${!args}

上面是我在学习shell编程时候看到的代码,我不明白为什么不直接用args,还要在前面放一个 !号,大家能帮我解释下吗??


如果不用!,lastarg是个数字,加上!那么是最后一个参数,不知道我的理解对不对。
另外一个例子:
args=3
lastarg=${!args}
则取到第三个参数
回复 支持 反对

使用道具 举报

发表于 2008-5-26 19:12:44 | 显示全部楼层
#! /bin/bash

args=$# # 位置参数的个数
lastarg=${!args}

可以这样解释,假设有5个参数a b c d e
那么$args=5
${!args}的意思是先把args展开,然后以args的值,也就是5,作为参数的名字再次展开作为表达式的值,也就是$5的值,这里就被扩展成了e。
顺便贴上bash手册中的介绍:
The basic form of parameter expansion is ${parameter}. The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character that is not to be interpreted as part of its name.

If the first character of parameter is [color="Red"]an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.
回复 支持 反对

使用道具 举报

发表于 2008-6-1 10:27:10 | 显示全部楼层
是间接引用。
args=3
$#的解析,楼上说很清楚。

如果args 是一个数字,就是$1,$2之类的,如果args不是一个数字,而是一个变量,就引用这个变量的值。
如t1=1
t2=t1
${!t2}与eval \$$t2相当,取t1的值1为值
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表