shell中的一些特殊变量

来源:互联网 发布:mysql num rows 错误 编辑:程序博客网 时间:2024/04/29 06:13

在bash中会用到很多特殊的shell变量,熟练运用这些变量会对bash编程有很大帮助。

 

shell中的特殊变量:

变量名

含义

$0

shellshell脚本的名字

$*

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

$@

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

$#

参数的个数

$_

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

$$

代表所在命令的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中类似的变量作比较,不同哦!:)

原创粉丝点击