(6)shell環境變數 CDPATH 用於cd命令的查找路徑 HOME /etc/passwd文件中列出的用戶主目錄 IFS Internal Field Separator,默認為空格,tab及換行符 MAIL /var/mail/$USERNAME mail等程序使用 PATH PS1,PS2 默認提示符($)及換行提示符(>) TERM 終端類型,常用的有vt100,ansi,vt200,xterm等
例: $ str1=abcd #在含有空格時必須用引號括起來 $ test $str1=abcd $ echo $? 0 $ str1="abcd " $ test $str1=abcd $ echo $? 1 Note: 在test處理含有空格的變數時最好用引號將變數括起來,否則會出現錯誤的 結果, 因為shell在處理命令行時將會去掉多餘的空格,而用引號括起來則可以防止 shell去掉這些空格. 例: $ str1=" " $ test $str1 $ echo $? 1 $ test "$str1" $ echo $? 0 $ test -n $str1 test: argument expected $ test -n "$str1" $ echo $? 0 $
b. 整數測試: test與expr相同,可以將字元型變數轉換為整數進行操作,expr進行 整數的算術運算,而test則進行邏輯運算.
表達式 說明 --------------------------------------- int1 -eq int2 相等? int1 -ne int2 不等? int1 -gt int2 int1 > int2 ? int1 -ge int2 int1 >= int2 ? int1 -lt int2 int1 empty $ test -r empty $ echo $? 0 $ test -s empty 1 $ test ! -s empty $ echo $? 0 e. 測試條件之邏輯運算 -a And -o Or
例: $ test -r empty -a -s empty $ echo $? 1 f. 進行test測試的標準方法 因為test命令在 shell編程中佔有很重要的地位,為了使shell能同其他編程語言 一樣 便於閱讀和組織, Bourne Shell在使用test測試時使用了另一種方法:用方括弧將 整個 test測試括起來:
$ int1=4 $ [ $int1 -gt 2 ] $ echo $? 0
例: 重寫unload程序,使用test測試 #!/bin/sh #unload - program to backup and remove files #syntax: unload directory
#check arguments if [ $# -ne 1 ] then echo "usage: $0 directory" exit 1 fi
#check for valid directory name if [ ! -d "$1" ] then echo "$1 is not a directory" exit 2 fi
cd $1
ls -a | cpio -o > /dev/rmt/0h
if [ $? -eq 0 ] then rm -rf * else echo "A problem has occured in creating backup" echo "The directory will not be ereased" echo "Please check the backup device" exit 3 fi # end of unload
until [ $# -eq 0 ] do echo "Argument is $1 and `expr $# - 1` argument(s) remain" shift done
$ shifter 1 2 3 4 Argument is 1 and 3 argument(s) remain Argument is 2 and 2 argument(s) remain Argument is 3 and 1 argument(s) remain Argument is 4 and 0 argument(s) remain $
#!/bin/sh # Interactive program to restore, backup, or unload # a directory
echo "Welcome to the menu driven Archive program"
while true do # Display a Menu echo echo "Make a Choice from the Menu below" echo _ echo "1 Restore Archive" echo "2 Backup directory" echo "3 Unload directory" echo "4 Quit" echo
# Read the user's selection echo -n "Enter Choice: "
read CHOICE
case $CHOICE in [1-3] ) echo # Read and validate the name of the directory
echo -n "What directory do you want? " read WORKDIR
if [ ! -d "$WORKDIR" ] then echo "Sorry, $WORKDIR is not a directory" continue fi
# Make the directory the current working directory cd $WORKDIR;;
4) :;; # :為空語句,不執行任何動作 *) echo "Sorry, $CHOICE is not a valid choice" continue esac
case "$CHOICE" in 1) echo "Restoring..." cpio -i /dev/rmt/0h;;
3) echo "Unloading..." ls | cpio -o >/dev/rmt/0h;;
4) echo "Quitting" break;; esac
#Check for cpio errors
if [ $? -ne 0 ] then echo "A problem has occurred during the process" if [ $CHOICE = 3 ] then echo "The directory will not be erased" fi
echo "Please check the device and try again" continue else if [ $CHOICE = 3 ] then rm * fi fi done