歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> 【shell腳本學習】shift命令學習

【shell腳本學習】shift命令學習

日期:2017/3/1 9:47:15   编辑:SHELL編程

位置參數可以用shift命令左移。比如shift 3表示原來的$4現在變成$1,原來的$5現在變成$2等等,原來的$1、$2、$3丟棄,$0不移動。不帶參數的shift命令相當於shift 1。

非常有用的 Unix 命令:shift。我們知道,對於位置變量或命令行參數,其個數必須是確定的,或者當 Shell 程序不知道其個數時,可以把所有參數一起賦值給變量$*。若用戶要求 Shell 在不知道位置變量個數的情況下,還能逐個的把參數一一處理,也就是在 $1 後為 $2,在 $2 後面為 $3 等。在 shift 命令執行前變量 $1 的值在 shift 命令執行後就不可用了。

測試命令如下:

[email protected]:/home/wl/桌面/shell# cat -n test.sh
1 #shift 命令(x_shift.sh)
2 until [ $# -eq 0 ]
3 do
4 echo "第一個參數為: $1 參數個數為: $#"
5 shift
6 done
[email protected]:/home/wl/桌面/shell#

輸出結果如下:

[email protected]:/home/wl/桌面/shell# chmod u+x test.sh
[email protected]:/home/wl/桌面/shell# ./test.sh a b c d e f g
第一個參數為: a 參數個數為: 7
第一個參數為: b 參數個數為: 6
第一個參數為: c 參數個數為: 5
第一個參數為: d 參數個數為: 4
第一個參數為: e 參數個數為: 3
第一個參數為: f 參數個數為: 2
第一個參數為: g 參數個數為: 1
[email protected]:/home/wl/桌面/shell#

Copyright © Linux教程網 All Rights Reserved