在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