在運行腳本程序中,用戶可以通過命令行參數將參數傳遞給腳本程序:
# ./test 10 a通過一些特殊的變量:位置參數,可以在腳本中取得命令行參數。其中,$0為程序名稱,$1為第一個參數,$2為第二個參數,依此類推 $9為第九個參數。# 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在第一次運行./test.sh時,沒有傳入參數,可以看出$1,$2值為空。每個參數都是通過空格分隔的,如果輸入的參數中包含空格,要用引號(" "或' ‘)包起來。# ./test.sh "hello world!" 2shell name is ./test.shfirst args is hello world!second args is 2如果命令行參數多于9個,如果想取得后面的參數,使用${10},${11}..,$(n)取得。雖然我們可以通過$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有時候我們僅僅想獲得程序的名稱(不包括具體路徑),可以使用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腳本中的命令行參數之前,必須對參數進行檢查,以保證命令行參數中確實包含我們想要的數據。$ 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、特殊的參數變量在bash shell中有一些特殊的參數變量,用于跟蹤命令行參數。(1)命令行參數個數變量$#記錄了腳本啟動時的命令行參數的個數。
# 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)命令行所有參數變量$*和$@包含了全部命令行參數(不包括程序名稱$0),變量$*將命令行的所有參數作為一個整體處理。而$@將所有參數當作同一個字符串的多個單詞處理,允許對其中的值進行迭代。# 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下面這個例子展示了$*和$@的不同之處# 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、命令行參數移位bash shell提供shift命令幫助操作命令行參數,shift命令可以改變命令行參數的相對位置,默認將每個參數左移一個位置,$3的值移給$2,$2的值移給$1,$1的值被丟棄。注意:$0的值和位置不受shift命令影響。$1移掉后,該參數值就丟失了,不能恢復。# 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命令可以帶一個參數實現多位移變化,命令行參數向左多個位置。# 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
新聞熱點
疑難解答