shell中的一些特殊变量 [转]

本文详细介绍了Bash中常用的特殊变量及其应用场景,并通过实例对比了$*与$@的区别。

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

转载于:https://www.cnblogs.com/starspace/archive/2008/11/13/1332892.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值