shell的特殊变量

1055阅读 0评论2008-07-15 fengshihua
分类:

在RHCE培训的时候还是有点迷糊的,今天总算搞比较清楚了.
$0
 shell或shell脚本的名字
 
$*
 以一对双引号给出参数列表
 
$@
 将各个参数分别加双引号返回 “$*”和“$@”相同,但$*和$@不同(见下面的test case)
 
$#
 参数的个数
 
$_
 代表上一个命令的最后一个参数
 
$$
 代表所在命令的PID
 
$!
 代表最后执行的后台命令的PID
 
$?
 代表上一个命令执行后的退出状态
 
e.g.
编辑如下test.sh脚本
#!/bin/bash
echo $0
echo $*
echo $@
echo $#
echo $$
ls -a /home
echo $_
在terminal窗口中执行:
./test.sh -a -b -c /home
./test.sh
-a -b -c /home
-a -b -c /home
4
3250
. .. fy jodier sky xk zhj
/home
----------------------------------------
echo $?
0
echo $!
 
ls -a /home &
[1] 3302
----------------------------------------------
为了区别$*和$@编写如下test.sh脚本:
#!/bin/bash
function testargs
{
echo "$# args"
}
testargs "$*"
testargs "$@"
unset -f testargs
在terminal窗口中执行:
./test.sh -a -b /home
1 args
3 args
-------------------------------------------------------
这里有一个很有意思的问题,如果test.sh为如下的内容:
#!/bin/bash
function testargs
{
echo "$# args"
}
testargs $*  #去掉双引号
testargs $@  #去掉双引号
unset -f testargs
再次执行有:
 ./test.sh -a -b /home
3 args
3 args
 
上一篇:告别KD
下一篇:经典爱情26个字母