1. 程式人生 > >Linux shell指令碼——if運算例子

Linux shell指令碼——if運算例子

下面以具體例子來描述shell指令碼中if語句的使用

#!/bin/sh

#define a variable,定義一個變數,此處等號兩邊不能有空格
v="test shell commond"
#print the variable,且沒有連字元也是支援的
echo "變數 is: " $v

#判斷當前目錄下是否有此檔案

file="test.sh" #定義要查詢的檔案

#[ -f "somefile" ] :判斷是否是一個檔案

if [ -f "$file" ];then #此處需要注意的是,if後面要有空格,且[後面、]前面都要有空格,然後是分號,最後是then
   echo "001"
else
   echo "002"
fi

#根據設定的數字大小來進行判斷,然後輸出結果


num=8
echo "the number is: " $num
if [ $num -gt 10 ];then
   echo "the unmber is larger than 10"
elif [ $num -eq 10 ];then
   echo "the number is equal with 10"
else
   echo "the number is smaller than 10"

fi

以下為網路中牛人總結的內容,可供參考使用。

shell判斷檔案,目錄是否存在或者具有許可權

#!/bin/sh
myPath="/var/log/httpd/"
myFile="/var /log/httpd/access.log"
#這裡的-x 引數判斷$myPath是否存在

並且是否具有可執行許可權
if [ ! -x "$myPath"]; then
mkdir "$myPath"
fi
#這裡的-d 引數判斷$myPath是否存在
if [ ! -d "$myPath"]; then
mkdir "$myPath"
fi
#這裡的-f引數判斷$myFile是否存在
if [ ! -f "$myFile" ]; then
touch "$myFile"
fi
#其他引數還有-n,-n是判斷一個變數是否是否有值
if [ ! -n "$myVar" ]; then
echo "$myVar is empty"
exit 0
fi
#兩個變數判斷是否相等

if [ "$var1" = "$var2" ]; then
echo '$var1 eq $var2'
else
echo '$var1 not eq $var2'
fi

========================================
shell 判斷語句

流程控制 "if" 表示式 如果條件為真則執行then後面的部分:

if ....; then
....
elif ....; then
....
else
....
fi

大多數情況下,可以使用測試命令來對條件進行測試。比如可以比較字串判斷檔案是否存在是否可讀等等…   

通常用" [ ] "來表示條件測試。注意這裡的空格很重要。要確保方括號的空格。
[ -f "somefile" ] :判斷是否是一個檔案
[ -x "/bin/ls" ] :判斷/bin/ls是否存在並有可執行許可權
[ -n "$var" ] :判斷$var變數是否有值
[ "$a" = "$b" ] :判斷$a和$b是否相等         

-r file     使用者可讀為真
-w file     使用者可寫為真
-x file     使用者可執行為真
-f file     檔案為正規檔案為真
-d file     檔案為目錄為真
-c file     檔案為字元特殊檔案為真
-b file     檔案為塊特殊檔案為真
-s file     檔案大小非0時為真
-t file     當檔案描述符(預設為1)指定的裝置為終端時為真

######################################################### 含條件選擇的shell指令碼
    對於不含變數的任務簡單shell指令碼一般能勝任。但在執行一些決策任務時,就需要包含if/then的條件判斷了。shell指令碼程式設計支援此類運算,包 括比較運算、判斷檔案是否存在等。基本的if條件命令選項有:
-eq —比較兩個引數是否相等(例如,if [ 2 –eq 5 ])
-ne —比較兩個引數是否不相等
-lt —引數1是否小於引數2
-le —引數1是否小於等於引數2
-gt —引數1是否大於引數2
-ge —引數1是否大於等於引數2
-f — 檢查某檔案是否存在(例如,if [ -f "filename" ])
-d — 檢查目錄是否存在
幾 乎所有的判斷都可以用這些比較運算子實現。指令碼中常用-f命令選項在執行某一檔案之前檢查它是否存在。
################################################################## 判斷檔案是否存在 #!/bin/sh
today=`date -d yesterday +%y%m%d`
file="apache_$today.tar.gz"
cd /home/chenshuo/shell
if [ -f "$file" ];then
echo "OK"
else
echo "error $file" >error.log
mail -s "fail backup from test" [email protected] <error.log
fi


相關推薦

no