Shell中的條件判斷

2021-10-14 01:52:05 字數 1116 閱讀 7910

1.基本語法

[ condition ] (注意condition 前後要有空格)

條件非空即為true,[ hyh ] 返回 true, 返回false。

2.常用判斷條件

(1)兩個整數之間的比較

= 字串比較

-lt(less than) 小於 <

-eq(equal) 等於 =

-le(less equal) 小於等於 <=

-gt(greater than) 大於 >

-ge(greater equal) 大於等於 >=

-ne(not equal) 不等於 !=

[hyh@localhost ~]$ [ 21 -lt 22 ]

[hyh@localhost ~]$ echo

$?0

(2)按照檔案許可權進行判斷

-r (read) 有讀的許可權

-w (write) 有寫的許可權

-x (execute) 有執行的許可權

[root@localhost myshells]

# [ -w var.sh ]

[root@localhost myshells]

# echo $?

0

(3)按照檔案型別進行判斷

-f(file)檔案存在並且是乙個常規的檔案

-d(directory) 檔案存在並且是乙個目錄

-e(existence) 檔案存在

-l(link) 檔案存在且是乙個鏈結

-s 檔案存在且不為空

[root@localhost myshells]

# [ -d /opt/myshells/ ]

[root@localhost myshells]

# echo $?

0

[hyh@localhost ~]$ [ con ]

&&echo ok ||

echo not ok

ok[hyh@localhost ~]$ [ con ]&&[

]||echo not ok

not ok

shell中條件判斷if

a file 如果file存在則為真。b file 如果file存在且是乙個塊特殊檔案則為真。c file 如果file存在且是乙個字特殊檔案則為真。d file 如果file存在且是乙個目錄則為真。e file 如果file存在則為真。f file 如果file存在且是乙個普通檔案則為真。g fi...

shell中if判斷條件

if 的三種條件表示式 ifcommand then if函式 then 命令執行成功,等於返回0 比如grep 找到匹配 執行失敗,返回非0 grep,沒找到匹配 if expression r r r then 表示式結果為真,則返回0,if把0值引向then if test expressio...

shell中if條件判斷

整數測試 字元測試 檔案測試 1 條件測試表示式 expression 括號兩端必須要有空格 expression 括號兩端必須要有空格 test expression 組合測試條件 a and o or 取非 2 整數比較 eq 測試兩個整數是否相等 ne 測試兩個整數是否不等 gt 測試乙個數是...