shell特殊位置变量

1.shell中特殊且重要的变量

1.1 shell中的特殊位置参数变量

在shell脚本中有一些特殊且重要的变量,例如:$0、$1、$#,称它们为特殊位置参数变量。需要从命令行、函数或脚本执行等传参时就要用到位置参数变量。下图为常用的位置参数:

shell特殊位置变量

(1) $1 $2...$9 ${10} ${11}特殊变量实战

范例1:设置15个参数($1~$15),用于接收命令行传递的15个参数。

[root@shellbiancheng ~]# echo \${1..15}
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
[root@shellbiancheng ~]# echo echo \${1..15}
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
[root@shellbiancheng ~]# echo echo \${1..15}>m.sh
[root@shellbiancheng ~]# cat m.sh 
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
[root@shellbiancheng ~]# echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z

执行结果如下:

[root@shellbiancheng ~]# sh m.sh {a..z}
a b c d e f g h i a0 a1 a2 a3 a4 a5

当位参数数字大于9时,需要用大括号引起来

[root@shellbiancheng ~]# cat m.sh 
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15}
[root@shellbiancheng ~]# sh m.sh {a..z}
a b c d e f g h i j k l m n o

(2)$0特殊变量的作用

$0的作用为取出执行脚本的名称(包括路径)。

范例2:获取脚本的名称及路径

[root@shellbiancheng jiaobenlianxi]# cat b.sh
echo $0

不带路径输出脚本的名字

[root@shellbiancheng jiaobenlianxi]# sh b.sh 
b.sh

带全路径执行脚本输出脚本的名字还有路径

[root@shellbiancheng jiaobenlianxi]# sh /home/linzhongniao/jiaobenlianxi/b.sh 
/home/linzhongniao/jiaobenlianxi/b.sh

有关$0的系统生产场景如下所示:

[root@shellbiancheng ~]# tail -6 /etc/init.d/rpcbind 
echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart|try-restart}"
RETVAL=2
;;
esac
exit $RETVAL

(3)$#特殊变量获取脚本传参个数实战

范例3:$#获取脚本传参的个数

[root@shellbiancheng ~]# cat m.sh  
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15}
echo $#
[root@shellbiancheng ~]# sh m.sh {a..z}
a b c d e f g h i j k l m n o  只接受15个变量,所以打印9个参数
26  传入26个字符作为参数

(4)$*和$@特殊变量功能及区别说明

范例4:利用set设置位置参数(同命令行脚本的传参)

[root@shellbiancheng ~]# set -- "I am" linzhongniao
[root@shellbiancheng ~]# echo $#
2
[root@shellbiancheng ~]# echo $1
I am
[root@shellbiancheng ~]# echo $2
linzhongniao

测试$*和$@,不带双引号

[root@shellbiancheng ~]# echo $*
I am linzhongniao
[root@shellbiancheng ~]# echo $@
I am linzhongniao

带双引号

[root@shellbiancheng ~]# echo "$*"
I am linzhongniao
[root@shellbiancheng ~]# echo "$@"
I am linzhongniao
[root@shellbiancheng ~]# for i in "$*";do echo $i;done $*引用,引号里的内容当做一个参数输出
I am linzhongniao
[root@shellbiancheng ~]# for i in "$@";do echo $i;done $@引用,引号里的参数均以独立的内容输出
I am
linzhongniao

猜你喜欢

转载自blog.51cto.com/10642812/2298641
今日推荐