歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux中的shell語句變量編程

Linux中的shell語句變量編程

日期:2017/3/1 16:20:13   编辑:SHELL編程
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
Copyright © Linux教程網 All Rights Reserved