Linux下shell腳本判斷文件相關屬性


先寫一些基本語法:

1、字符串判斷

str1 = str2      當兩個串有相同內容、長度時為真
str1 != str2      當串str1和str2不等時為真
-n str1         當串的長度大於0時為真(串非空)
-z str1         當串的長度為0時為真(空串)
str1           當串str1為非空時為真

2、數字的判斷

int1 -eq int2    兩數相等為真
int1 -ne int2    兩數不等為真
int1 -gt int2    int1大於int2為真
int1 -ge int2    int1大於等於int2為真
int1 -lt int2    int1小於int2為真
int1 -le int2    int1小於等於int2為真

3 文件的判斷

-r file     用戶可讀為真
-w file     用戶可寫為真
-x file     用戶可執行為真
-f file     文件為正規文件為真
-d file     文件為目錄為真
-c file     文件為字符特殊文件為真
-b file     文件為塊特殊文件為真
-s file     文件大小非0時為真
-t file     當文件描述符(默認為1)指定的設備為終端時為真

4 復雜邏輯判斷

-a         與
-o        或
!        非


下面是一些使用實例:

#!/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
  if list then
    do something here
  elif list then
    do another thing here
  else
    do something else here
fi


EX1:

#!/bin/sh

SYSTEM=`uname -s`     #獲取操作系統類型,我本地是linux

if [ $SYSTEM = "Linux" ] ; then     #如果是linux的話打印linux字符串
echo "Linux"
elif [ $SYSTEM = "FreeBSD" ] ; then  
echo "FreeBSD"
elif [ $SYSTEM = "Solaris" ] ; then
echo "Solaris"
else
echo "What?"
fi     #ifend


基本上和其他腳本語言一樣。沒有太大區別。不過值得注意的是。[]里面的條件判斷。

原文鏈接:http://www.linuxidc.com/Linux/2012-03/55660.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM