在運(yùn)行腳本程序中,用戶可以通過(guò)命令行參數(shù)將參數(shù)傳遞給腳本程序:
# ./test 10 a通過(guò)一些特殊的變量:位置參數(shù),可以在腳本中取得命令行參數(shù)。其中,$0為程序名稱,$1為第一個(gè)參數(shù),$2為第二個(gè)參數(shù),依此類推 $9為第九個(gè)參數(shù)。# cat test.sh #!/bin/bashecho "shell name is $0"echo "first args is $1"echo "second args is $2"# ./test.sh shell name is ./test.shfirst args is second args is # ./test.sh 1 2 shell name is ./test.shfirst args is 1second args is 2在第一次運(yùn)行./test.sh時(shí),沒(méi)有傳入?yún)?shù),可以看出$1,$2值為空。每個(gè)參數(shù)都是通過(guò)空格分隔的,如果輸入的參數(shù)中包含空格,要用引號(hào)(" "或' ‘)包起來(lái)。# ./test.sh "hello world!" 2shell name is ./test.shfirst args is hello world!second args is 2如果命令行參數(shù)多于9個(gè),如果想取得后面的參數(shù),使用${10},${11}..,$(n)取得。雖然我們可以通過(guò)$0確定程序的名稱,但是$0中包括程序完整的路徑。# cat test.sh#!/bin/bashecho "shell name is $0"# ./test.shshell name is ./test.sh# /home/jie/code/shellcode/test.sh shell name is /home/jie/code/shellcode/test.sh有時(shí)候我們僅僅想獲得程序的名稱(不包括具體路徑),可以使用basename命令取得程序名稱(name=`basename $0`)。# cat test.sh#!/bin/bashname=`basename $0`echo "shell name is $name"# ./test.shshell name is test.sh# /home/jie/code/shellcode/test.sh shell name is test.sh在使用shell腳本中的命令行參數(shù)之前,必須對(duì)參數(shù)進(jìn)行檢查,以保證命令行參數(shù)中確實(shí)包含我們想要的數(shù)據(jù)。$ cat test.sh#!/bin/bashif [ -n "$1" ]then echo "hello $1!"else echo "Please input a name!"fi$ ./test.sh mikehello mike!$ ./test.sh Please input a name!2、特殊的參數(shù)變量在bash shell中有一些特殊的參數(shù)變量,用于跟蹤命令行參數(shù)。(1)命令行參數(shù)個(gè)數(shù)變量$#記錄了腳本啟動(dòng)時(shí)的命令行參數(shù)的個(gè)數(shù)。
# cat test.sh#!/bin/bashecho "the count of args is : $#"# ./test.sh 1 2 3 4 the count of args is : 4# ./test.sh 1 2 3 4 5 6 "hello"the count of args is : 7(2)命令行所有參數(shù)變量$*和$@包含了全部命令行參數(shù)(不包括程序名稱$0),變量$*將命令行的所有參數(shù)作為一個(gè)整體處理。而$@將所有參數(shù)當(dāng)作同一個(gè)字符串的多個(gè)單詞處理,允許對(duì)其中的值進(jìn)行迭代。# cat test.sh #!/bin/bashecho "Using the /$* method:$*"echo "Using the /$@ method:$@"# ./test.sh 1 2 3 Using the $* method:1 2 3Using the $@ method:1 2 3下面這個(gè)例子展示了$*和$@的不同之處# cat test.sh#!/bin/bashcount=1for param in "$*"do echo "/$* Parameter #$count = $param" count=$[$count+1]donecount=1for param in "$@"do echo "/$@ Parameter #$count = $param" count=$[$count+1]done# ./test.sh 1 2 3$* Parameter #1 = 1 2 3$@ Parameter #1 = 1$@ Parameter #2 = 2$@ Parameter #3 = 33、命令行參數(shù)移位bash shell提供shift命令幫助操作命令行參數(shù),shift命令可以改變命令行參數(shù)的相對(duì)位置,默認(rèn)將每個(gè)參數(shù)左移一個(gè)位置,$3的值移給$2,$2的值移給$1,$1的值被丟棄。注意:$0的值和位置不受shift命令影響。$1移掉后,該參數(shù)值就丟失了,不能恢復(fù)。# cat test.sh#!/bin/bashcount=1while [ -n "$1" ]do echo "Parameter #$count = $1" count=$[$count+1] shiftdoneecho "/$#=$#"echo "/$*=$*"echo "/$@=$@"echo "/$1=$1"# ./test.sh 1 2 3 Parameter #1 = 1Parameter #2 = 2Parameter #3 = 3$#=0$*=$@=$1=shift命令可以帶一個(gè)參數(shù)實(shí)現(xiàn)多位移變化,命令行參數(shù)向左多個(gè)位置。# cat test.sh#!/bin/bashecho "The origin parameters are:$*"shift 2echo "after shift 2 the parameters are:$*"# ./test.sh 1 2 3 4 5 The origin parameters are:1 2 3 4 5after shift 2 the parameters are:3 4 5
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注