語法:
read variable [variable......]
例子:
$ cat color6
echo This program prompts for user input
echo “please enter your favorite two colors -> \c”
read color_a color_b
echo The colors you entered are: $color_b $color_a
$ chmod +x color6
$ color6
This program prompts for user input
Please enter your favorite two colors -> red blue
The colors you entered are: blue red
$ color6
This program prompts for user input
Please enter you favorite two colors -> red blue tan
The color you enterd are :blue tan red
用戶使用命令行參數(shù)傳遞信息進(jìn)程序,在命令執(zhí)行之前,用戶必須知道正確的語法。有一種情況,你想要在用戶執(zhí)行程序的時候提示他輸入這些參數(shù)。read命令就是用來在程序執(zhí)行的時候收集終端鍵入的信息。
你通常會想要使用echo命令來提供用戶一個提示,讓他知道程序正在等待一些輸入,同時通知用戶應(yīng)該輸入的類型。因此,每一個read命令應(yīng)該在echo命令前面。
read命令會給出一個變量名的列表,這些變量會被用戶在提示符下輸入的詞賦值。(以空格分隔)。如果read命令定義的變量比輸入的詞要多,剩余變量會被賦空值。如果用戶輸入的詞要比變量多,剩余的數(shù)據(jù)會賦給列表中的最后一個變量。
一旦被賦值,你就可以象其他的shell變量一樣存取這些變量。
注意:不要混淆位置參數(shù)和變量read。位置參數(shù)在命令被激活時在命令行中定義
read命令給變量賦值是在程序執(zhí)行之中,通過對輸入提示的響應(yīng)而給變量賦值。
以下例子提示用戶輸入要被安裝的文件名:
$ cat > my_install3
echo $0 will install files into your bin directory
echo “Enter the names of the files -> \c”
read filenames
mv $filenames $HOME/bin
echo Instllation is complete
ctrl + d
$ chmod +x my_install13
$ my_install13
my_install13 will install files into your bin directory
Enter the names of the files -> f1 f2
Installaton is complete
這個安裝會提示用戶輸入chmod和移動到$HOME/bin的文件名。這個程序給用戶更多的關(guān)于應(yīng)該輸入數(shù)據(jù)情況的指引。而不像install2中用戶必須在命令行中提供文件名。用戶使用程序不需要特殊的語法。程序讓用戶確切地知道要輸入什么。所有的輸入的文件名都會被賦值給變量filenames。
1.8 另外的技術(shù)
#號開始的文檔為注釋部分。
sh shell_program argumetns?
shell_program 的屬性可以不是可執(zhí)行的。
shell_program 必須是可讀的。
sh –x shell_program arguments
每一行在被執(zhí)行前被打印出來在調(diào)試程序時有用處。
在shell程序中,#符號被用來提供一段注釋。shell會忽略#符號后邊的字符,直到一個回車符號為止。
執(zhí)行一個shell程序的另外一種方法是:sh shell_program arguments
這種方式激活一個子shell并且指定這個子shell為執(zhí)行這個程序的命令解釋器。這個程序文件不是必須為可執(zhí)行的。這種方式的用途在:你正在在一種shell下工作,同時想要執(zhí)行用其他shell命令語言寫的shell程序十分有用。
你也可以在你的shell程序的第一行前加入#!/usr/bin/ shell_name來指定命令行解釋器。因此,如果你當(dāng)前正在POSIX shell下工作,但是想要執(zhí)行一個C shell的腳本,你的C shell程序的第一行應(yīng)該為:
#!/usr/bin/csh
雖然shell程序沒有調(diào)試器,命令:
sh –x shell_program arguments
會在執(zhí)行每一行時,先在屏幕上打印出shell程序的每一行。這允許你看到shell如何進(jìn)行文件名產(chǎn)生,變量替代,和命令替代。這個選項對發(fā)現(xiàn)打字錯誤十分有幫助。