1、移動變量
腳本 sh05.sh
#!/bin/bash # Program # Program shows the effect of shift function # History: # 2015/9/6 zengdp First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH echo "Total parameter number is ==> $#" echo "You whole parameter is ==> '$@'" shift echo "Total parameter number is ==> $#" echo "You whole parameter is ==> '$@'" shift 3 echo "Total parameter number is ==> $#" echo "You whole parameter is ==> '$@'"
運行 sh sh05.sh one two three four five six
得到
Total parameter number is ==> 6 You whole parameter is ==> 'one two three four five six' Total parameter number is ==> 5 You whole parameter is ==> 'two three four five six' Total parameter number is ==> 2 You whole parameter is ==> 'five six'
光看結果你就可以知道啦,那個 shift 會移動變量,而且 shift 后面可以接數字,代表拿掉最前面的幾個參數的意思。 上面的運行結果中,第一次進行 shift 后他的顯示情況是『 one two three four five six』,所以就剩下五個啦!第二次直接拿掉三個,就變成『 two three four five six 』啦!
2、 當使用shift移動一個變量時,使用while輸出第一個變量,從而輸出在輸入時所有的變量
文件名為 test13.sh
1 #!/bin/bash 2 # demostrating the shift command 3 4 count=1 5 while [ -n "$1" ] 6 do 7 echo "Parameter #$count=$1" 8 count=$[$count + 1] 9 shift 10 done
腳本執行一個while循環,測試第一個參數的長度,當第一個參數值長度為0時,結束循環,測試第一個參數后,使用shift命令將所有參數左移一個位置
sh test13.sh rich barbara katie jessica
輸出為:
Parameter #1=rich Parameter #2=barbara Parameter #3=katie Parameter #4=jessica
3、從參數中分離選項
執行shell腳本時經常會遇到既需要使用選項有需要使用參數的情況,在Linux中的標準方式是通過特殊字符嗎將二者分開,這個特殊字符嗎告訴腳本選項結束和普通參數開始的位置
對于Linux,這個特殊字符嗎就是雙破折號(--),shell使用雙破折號知識選項列表的結束,發現雙破只好后,腳本就能夠安全的將剩余的命令行參數作為參數而不是選項處理
文件名為 test16.sh
1 #!/bin/bash 2 # extracting options and parameters 3 4 while [ -n "$1" ] 5 do 6 case "$1" in 7 -a) echo "Found the -a option" ;; 8 -b) echo "Found the -b option";; 9 -c) echo "Found the -c option" ;; 10 --) shift 11 break ;; 12 *) echo "$1 is not an option";; 13 esac 14 shift 15 done 16 17 count=1 18 for param in $@ 19 do 20 echo "Parameter #$count: $param" 21 count=$[ $count + 1 ] 22 done
這個腳本使用break命令使得遇到雙破折號時從while循環中跳出,因為提前從循環中跳出,所以需要保證加入一個shift命令將雙破折號從參數變量中丟棄
第一個測試,嘗試使用普通選項和參數集運行腳本
sh test16.sh -a -b -c test1 test2 test3
輸出為:
Found the -a option Found the -b option Found the -c option test1 is not an option test2 is not an option test3 is not an option
第二次測試,使用雙破折號將命令行中選項和參數分開
sh test16.sh -a -b -c -- test1 test2 test3
輸出結果為
Found the -a option Found the -b option Found the -c option Parameter #1: test1 Parameter #2: test2 Parameter #3: test3
這時可以看到輸出的結果中,因為識別到'--'符號,便跳出了while循環,然后使用下一個循環中輸出剩下的變量
文章列表