Linux中的shell語句變數編程 shell變數 1:兩類變數:臨時變數和永久變數 臨時變數是shell程式內部定義的,適用範圍僅限於程式內部,對其他程式不可見。包括:使用者自訂變數,位置變數。永久變數是環境變數,其值不隨shell指令碼的執行結束而消失。 2:使用者自訂變數要以字母或底線開頭,由字母,數字,底線組成。在使用變數時,要在變數前面加"$"符號。 3:位置變數和特殊變數 shell解釋執行使用者命令時,將執行命令的第一個部分作為命令名,其他部分作為參數。由出現在命令列上的位置確定的參數稱為位置參數。 例如: ls -l file1 file2 file3 $0這個程式的檔案名稱 ls -l $n 這程式的第n個參數值,n=1-9 4:特殊變數 $* 這個程式的所有的參數 $# 這個程式的參數的個數 $$ 這個程式的PID $! 執行上一個後台命令的PID $? 執行上一個命令的傳回值 5:shell命令 read命令:從鍵盤讀入資料,付給變數。 如:read NAME expr命令:對整數型變數進行算數運算 如:expr 3 + 5 之間要有空格否則以字元的形式表示出來 expr $var1 / $var2 同上 expr $var1 \* 10 乘法要用到逸出字元"\" 複雜的運算:expr `expr 5 + 7` + 3 可以用命令替換符 6:變數測試語句: test 測試條件 1>字串測試: test str1=str2 測試字串是否相等 test str1 != str2 測試字串是否不相等 test str1 測試字串str1是否不為空白 test -n str1 測試字串是否不為空白 test -z str1 測試字串是否為空白 2>整數測試: test int1 -eq int2 測試整數是否相等 test int1 -ge int2 測試int1是否>=int2 test int1 -gt int2 測試int1是否> int2 test int1 -le int2 測試int1是否 <= int2 test int1 -lt int2 測試int1是否< int2 test int1 -ne int2 測試int1和int2是否不相等 3>檔案測試: test -d file 指定的問件是否為目錄 test -f file 指定的檔案是否為常規的檔案 test -x file 指定的檔案是否可執行 test -r file 指定的檔案是否可讀 test -w file 指定的檔案是否可寫 test -a file 指定的檔案是否存在 test -s file 指定的檔案大小是否非0變數測試語句一般不單獨使用,一般作為if語句的測試條件。例如: if test -d $1 then fi變數測試語句可用[] 進行簡化,如test -d $1 等價於 [ -d $1 ] (注意括弧兩邊的空格) 7:流程式控制制語句 多個條件的聯合: -a 邏輯與,若且唯若兩個條件都成立時,結果為真 -o 邏輯或,兩個條件只要有一個條件成立,結果為真。 例如: elif [ -c $file_name -o -b $file_name ] then (注意測試語句內的空格) 一個實際的例子: #/bin/sh if [ $# -ne 2 ]; then echo "Not enough parameters" exit 0 # 0表示程式正常的退出 fi if [ $1 -eq $2 ]; then echo "$1 equals $2" #注意雙引號和單引號的區別 elif [ $1 -lt $2 ]; then echo "$1 littler than $2" elif [ $1 -gt $2 ]; then echo "$1 greater than $2" fi for ....done語句 例子:(剔除某一個線上的使用者) #!/bin/sh #the script to kill logined user username="$1" /bin/ps aux | /bin/grep $username | /bin/awk '{ print $2 }' > /tmp/tmp.pid killid = `cat /tmp/tmp.pid` for PID in $killid do /bin/kill -9 $PID 2> /dev/null done