【文章內容簡介】
$2等等。在 $9以后,必須使用括號: $(10),$(11),否則, shell會將 $10看成是 $1后面跟一個 0。而 $0會一直保存程序或命令的名字 shell程序的參數(繼續(xù)) 以下的 shell程序會安裝一個程序,這個程序作為一個命令行參數被安裝到你的 bin目錄:首先創(chuàng)建程序 my_install,注意 目錄 $HOME/bin應該預先存在。 $ cat my_install echo $0 will install $1 to your bin directory chmod +x $1 mv $1 $HOME/bin echo Installation of $1 is plete ctrl + d $ chmod +x my_intalll $ my_install color3 my_install will install color3 to your bin directory Installation of color3 is plete $ 這個例子中,程序指明第一個命令行參數為一個文件名,然后加 上執(zhí)行權限,然后移動到你當前目錄下的 bin目錄下。 記住 UNIX系統(tǒng)的慣例是存貯程序在 bin的目錄下。你也許想要在你的 HOME目錄下創(chuàng)建一個 bin目錄,在這個目錄下你可以存儲你的程序文件,記住要將你的 bin目錄放在 PATH環(huán)境變量中,這樣 shell才會找到你的程序。 一些特殊 shell變量- #和 * * 例子: $ cat color4 echo There are $ and line argument echo They are $* ehco The first mand line argument is $1 $ chmod +x color4 $ color4 red green yellow blue They are 4 mand line arguments They are red green yellow blue The first mand line argument is red $ 至今為止我們看到的 shell程序都不是很靈活, 如 color3需要輸入兩個正確的參數而my_install 只 需要一個 。通常在創(chuàng)建一個接收命令行參數的 shell 程序的時候,你想要用戶輸入一個參數的變量號碼。你同時要程序執(zhí)行成功,不管用戶鍵入 1 個參數或是 20 個參數。當處理變量參數列表的時候,特殊 shell 變量會提供你許多的靈活性。通過 $你可以知道有多少參數已經被輸入,通過 $*可以存取全部的參數列表,而不管參數的數量。請注意參數( $0)不在 $*這個參數列表里。 每一個命令行參數都是互相獨立的,你可以通過 $*集中檢索這些參數,也可以通過$1,$2,$3等等來獨立的檢索這些參數。 一些特殊的 shell變量-#和 *(繼續(xù) ) 一個可以接收多個命令行參數的安裝程序的例子: $ 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 plete 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 plete 這個安裝程序更加靈活,如果你有多個文件要安裝,你僅需要執(zhí)行這個程序一次,只要一次輸入多個名字即可。