您的位置:首页 > 运维架构 > Shell

shell中的一些特殊变量

2010-04-24 23:19 375 查看
在bash中会用到很多特殊的shell变量,熟练运用这些变量会对bash编程有很大帮助。

shell
中的特殊变量:

变量名

含义

$0

shell
或shell
脚本的名字
$*

以一对双引号给出参数列表

$@

将各个参数分别加双引号返回

$#

参数的个数

$_

代表上一个命令的最后一个参数

$$

代表所在命令的
PID

$!

代表最后执行的后台命令的
PID

$?

代表上一个命令执行后的退出状态

e.g.

编辑如下
test.sh
脚本

#!/bin/bash

echo $0

echo $*

echo $@

echo $#

echo $$

ls -a /home

echo $_


terminal
窗口中执行:

xk@linux:~/work>
./test.sh -a -b -c /home

./test.sh

-a -b -c
/home

-a -b -c
/home

4

3250

. .. fy
jodier sky xk zhj

/home

xk@linux
:~/work>echo $?

0

xk@linux:
~/work>echo $!

xk@linux:~/work>
ls -a /home &

[1] 3302

xk@linux:~/work>
. .. fy jodier sky xk zhj

[1]+ Done
/bin/ls $LS_OPTIONS -a /home

xk@linux:~/work>
echo $!

3302

xk@linux:~/work>

为了区别
$*

$@
编写如下
test.sh
脚本:

#!/bin/bash

function
testargs

{

echo "$#
args"

}

testargs
"$*"

testargs
"$@"

unset -f
testargs


terminal
窗口中执行:

xk@linux:~/work>
./test.sh -a -b /home

1 args

3 args

xk@linux
:~/work>

这里有一个很有意思的问
题,如果
test.sh
为如下的内容:

#!/bin/bash

function
testargs

{

echo "$#
args"

}

testargs $*

testargs $@

unset -f
testargs

再次执行有:

xk@linux:~/work>
./test.sh -a -b /home

3 args

3 args

xk@linux
:~/work>

呵呵,这个问题稍后的文章
会有解释。

另,这些特殊的
shell
变量可以和
perl
中类似的变量作比较,不同哦!:)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: