shell常用的判斷條件

2022-05-05 22:30:14 字數 3174 閱讀 6833

1

、判斷資料夾是否存在

if [ -d /home/q/www ];then echo "

true

"; else echo "

false

";fi

(系統內存在資料夾 /home/q/www)

2、判斷檔案是否存在

if [ -e /etc/passwd ];then echo "

true

"; else echo "

false

";fi

if [ -f /etc/passwd ];then echo "

true

"; else echo "

false

";fi

檔案存在且大小大於0

if [ -s /etc/passwd ];then echo "

true

"; else echo "

false

";fi

3、判斷檔案可讀

if [ -r /etc/passwd ];then echo "

true

"; else echo "

false

";fi

4、判斷檔案可寫

if [ -w /etc/passwd ];then echo "

true

"; else echo "

false

";fi

5、判斷檔案可執行

if [ -x /etc/passwd ];then echo "

true

"; else echo "

false

";fi

6、字串長度為0,返回真

長度為0

if [ -z "" ];then echo "

true

"; else echo "

false

";fi

長度不為0

if [ -z "

xiaoqiang

" ];then echo "

true

"; else echo "

false

";fi

7、字串長度不為0,返回真

長度不為0

if [ -n "

xiaoqiang

" ];then echo "

true

"; else echo "

false

";fi

長度為0

if [ -n "" ];then echo "

true

"; else echo "

false

";fi

8、判斷字串相等

if [ "

xiaoqiang

" = "

xiaoqiang

" ];then echo "

true

"; else echo "

false

";fi

9、判斷字串不相等

if [ "

xiaoqiang

" != "

xiaoqiang

" ];then echo "

true

"; else echo "

false

";fi

10、判斷整數相等

if [ 1 -eq 1 ];then echo "

true

"; else echo "

false

";fi

11、判斷整數不相等

if [ 1 -ne 1 ];then echo "

true

"; else echo "

false

";fi

12、判斷整數 1

< 2

if [ 1 -lt 2 ];then echo "

true

"; else echo "

false

";fi

13、判斷整數 2

<= 2

if [ 2 -le 2 ];then echo "

true

"; else echo "

false

";fi

14、判斷整數3 > 2

if [ 3 -gt 2 ];then echo "

true

"; else echo "

false

";fi

15、判斷整數 3 >= 3

if [ 3 -ge 3 ];then echo "

true

"; else echo "

false

";fi

16、邏輯運算

!(非)

if [ ! 3 -ge 3 ];then echo "

true

"; else echo "

false

";fi

-a(and)

if [ -z "" -a 3 -ge 3 ];then echo "

true

"; else echo "

false

";fi

-o(或)

if [ -z "

sadfsa

" -o 3 -ge 3 ];then echo "

true

"; else echo "

false

";fi

17、特殊變數

echo

"number:$#

"獲取引數個數

echo

"scname:$0

"獲取指令碼名稱

echo

"first:$1

"獲取第乙個引數

echo

"second:$2

"獲取第二個引數

echo

"argume:$@

"獲取所有引數

echo

"show parm list :$*

"資料引數的list

echo

"show process id :$$

"獲取程序id

echo

"show precomm stat:$?

" 獲取命令執行的結果

shell常用判斷條件if

r file 使用者可讀為真 w file 使用者可寫為真 x file 使用者可執行為真 f file 檔案為正規檔案為真 d file 檔案為目錄為真 c file 檔案為字元特殊檔案為真 b file 檔案為塊特殊檔案為真 s file 檔案大小非0時為真 t file 當檔案描述符 預設為1...

shell中常用檔案條件判斷

在shell指令碼經常碰到if的條件判斷語句,中括號中會出現 f d等用於判斷一些變數和檔案,例如 if x tmp fh before preconfig.sh x在此處就是用於判斷 fh before preconfig.sh是否可執行 現將shell中常見的條件判斷符總結歸納如下 常用檔案條件...

Shell條件判斷

b file 若檔案存在且是乙個塊特殊檔案,則為真 c file 若檔案存在且是乙個字元特殊檔案,則為真 d file 若檔案存在且是乙個目錄,則為真 e file 若檔案存在,則為真 f file 若檔案存在且是乙個規則檔案,則為真 g file 若檔案存在且設定了sgid位的值,則為真 h fi...