# ???命令行參數的數量
* ???完全的參數字符串
例子:
$ cat color4
echo There are $#?comand line argument
echo They are $*
ehco The first command line argument is $1
$ chmod +x color4
$ color4 red green yellow blue
They are 4 command line arguments
They are red green yellow blue
The first command line argument is red
$
至今為止我們看到的shell程序都不是很靈活。color3需要兩個正確的參數,而my_install只需要一個。通常在你創(chuàng)建一個接收命令行參數的shell程序的時候,你想要用戶輸入一個參數的變量號碼。你同時要程序執(zhí)行成功,不管用戶鍵入1個參數或是20個參數。
當處理變量參數列表的時候,特殊shell變量會提供你許多的靈活性。通過$#你可以知道有多少參數已經被輸入,通過$*可以存取全部的參數列表,而不管參數的數量。請注意參數($0)不在$*這個參數列表里。
每一個命令行參數都是互相獨立的,你可以通過$*集中檢索這些參數,也可以通過$1,$2,$3等等來獨立的檢索這些參數。
一個可以接收多個命令行參數的安裝程序的例子:
$ cat > my_install2
echo $0 will install $# files to your bin directory
echo The files to be installed are : $*
chmod +x $*
mv $* $HOME/bin
echo Installaton is complete
ctril + d
$ chmod +x my_install2
$ my_install2 color1 color2
my_intall2 will install 2 files to your bin directory
The files to be installed are: color1,color2
Intallaiton is complete
這個安裝程序更加靈活。如果你有幾個腳本要安裝,你僅僅需要執(zhí)行這個程序一次,只要輸入多個名字即可。
非常重要的是:如果你計劃傳遞整個參數的字符串給一個命令,這個命令必須能夠接收多個參數。
在以下的腳本中,用戶提供一個目錄名作為一個命令行參數。程序會更改到指定的目錄,顯示當前的位置,并且列出內容。
$ cat list_dir
cd $*
echo You are in the $(pwd) directory
echo The contents of the directory are:
ls –F
$ list_dir dir1 dir2 dir3
sh: cd: bad argument count
由于cd命令不能同時進入到多個目錄中,這個程序會發(fā)生錯誤。
1.6 shift 命令
向左移動所有的在*中的字符串n個位置
#的數目減少n個(n的默認值是1)
語法:shift [n]
例子:
$ cat color5
orig_args=$*
echo There are $# command line arguments
echo They are $*
echo Shifting two arguments
shift 2
echo There are $# comand line arguments
echo They are $*
echo Shifting two arguments
shift 2; final_args=$*
echo Original arguments are: $orig_args
echo Final arguments are: $final_args
shift命令會重新分配命令行參數對應位置參數,在shift n以后,所有的*中的參數會向左移動n個位置。同時#會減n。默認的n為1。Shift命令不會影響到參數0的位置。
一旦你完成一次移動,被移動出命令行的參數會丟失。如果你想在你的程序中引用這個參數,你需要在執(zhí)行shift之前存貯這個參數。
Shift命令被用在:存取一組參數的位置,例如一系列的x,y的坐標從命令行刪除命令選項,假定選項在參數之前。
例子:
$ color5 red green yellow orange black
There are 6 command line arguments
They are red green yellow blue orange black
Shifting two arguments
There are 4 command line arguments
They are yellow blue orange black
Shiftging two arguments
Original arguments are: red green yellow blue orange black
Final argument are : orange black
$