$ color = lavender
$ cat color1
echo you are now running program: color1
echo the value of the variable color is : $color
$ chmod +x color1
$ color1
you ar now running program : color1
the value of the variable color is :
$ export color
$ color1
you are now running program : color1
the value of the variable color is : lavender
傳遞數據給shell腳本的一種方法就是通過環境。在上例中。本地變量color被賦值為lavender。然后創建了shell程序color1;然后更改為可執行權限;然后這個shell程序被執行。color1試圖回送color變量的值。但是,由于color是一個本地變量,屬于父shell私有的,運行color1產生的子shell不能識別這個變量,因此不能打印出它的值。當color被輸出到環境中,它就可以被子shell讀取。
同樣,由于shell進程不能夠更改父進程的環境,對一個子進程中的環境變量重新賦值不會影響到父進程環境中的值。如以下的shell腳本中的color2。
echo The original value of the variable color is $color
ech0 This program will set the value of color to amber
color=amber
echo The value of color is now $color
echo When your program concludes,display the value of the color variable
觀察在你設置了color的值后有什么變化。輸出這個變量,然后執行color2:
$ export color=lavender
$ echo $color
lanvender
$ color2
The original value of the variable color is lavender
The program will set the value of color to amber
The value of volor is now amber
When your progam concludes, display the value of the color variable,
$ echo $color
lanvender
1.4 shell 程序的參數
命令行:
?$ sh_program arg1 arg2 . . . argx
???$0 ???$1?? $2 ....? $X
例子:
$ cat color3
echo you are now running program: $0
echo The value of command line argument \#1 is: $1
echo The value of command line argument \#2 is : $2
$ chmod +x color3
$ color3 red green
You are now running program: color3
The value of command line argument #1 is : red
The value of command line argument #2 is: green
大多數的UNIX系統命令可以接收命令行參數,這些參數通常告訴命令它將要操作的文件或目錄(cp f1 f2),另外指定的參數擴展命令的能力(ls –l),或者提供文本字符串(banner hi there)
命令行參數同樣對shell程序有效。這在于傳送信息給你的程序的時候十分方便。通過開發一個接收命令行參數的程序,你可以傳遞文件或者目錄命令名給你的程序處理,就像你運行UNIX系統命令一樣。你也可以定義命令行選項來讓命令行使用shell程序額外的功能。
在shell程序中的命令行參數與參數在命令行的位置相關。這樣的參數被稱為位置參數,因為對每一個特殊變量的賦值依靠一這些參數在命令行中的位置。這些變量的變量名對應它們在命令行中的數字位置,因此這些特殊的變量名為數字0,1,2等等,一直到最后的參數被傳遞。變量名的存取通過同樣的方法,在名字前面加上$ 符號,因此,為了存取你的shell程序中的命令行參數,你可以應用$0,$1,$2等等。在$9以后,必須使用括號:$(10),$(11),否則,shell會將$10看成是$1后面跟一個0。$0會一直保存程序或命令的名字。
以下的shell程序會安裝一個程序,這個程序作為一個命令行參數被安裝到你的bin目錄:首先創建程序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 complete
ctrl + d
$ chmod +x my_intalll
$ my_install color3
my_install will install color3 to your bin directory
Installation of color3 is complete
$
這個例子中,一個程序指明第一個命令行參數為一個文件名,然后加上執行權限,然后移動到你當前目錄下的bin目錄下。
記住UNIX系統的慣例是存貯程序在一個叫做bin的目錄下。你也許想要在你的HOME目錄下創建一個bin目錄,在這個目錄下你可以存儲你的程序文件,記住要將你的bin目錄放在PATH環境變量中,這樣shell才會找到你的程序。