在shell脚本中有一些特殊且重要的变量,例如:$0、$一、$#,称它们为特殊位置参数变量。须要从命令行、函数或脚本执行等传参时就要用到位置参数变量。下图为经常使用的位置参数:shell
(1) $1 $2...$9 ${10} ${11}特殊变量实战ide
范例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特殊变量的做用rest
$0的做用为取出执行脚本的名称(包括路径)。code
范例2:获取脚本的名称及路径rpc
[root@shellbiancheng jiaobenlianxi]# cat b.sh echo $0
不带路径输出脚本的名字it
[root@shellbiancheng jiaobenlianxi]# sh b.sh b.sh
带全路径执行脚本输出脚本的名字还有路径class
[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