2011-04-07 17:25

[轉載][Shell] if 條件式選項列表

轉載自:利用 test 指令的測試功能 - 鳥哥的 Linux 私房菜 -- 學習 Shell Scripts

1. 關於某個檔名的『檔案類型』判斷
標誌意義範例
-e$FILE 是否存在?(常用)if[ -e $FILE ]; then
-f$FILE 是否存在且為檔案(file)?(常用)if[ -f $FILE ]; then
-d$FILE 是否存在且為目錄(directory)?(常用)if[ -d $FILE ]; then
-b$FILE 是否存在且為一個 block device 裝置?if[ -b $FILE ]; then
-c$FILE 是否存在且為一個 character device 裝置?if[ -c $FILE ]; then
-S$FILE 是否存在且為一個 Socket 檔案?if[ -S $FILE ]; then
-p$FILE 是否存在且為一個 FIFO (pipe) 檔案?if[ -p $FILE ]; then
-L$FILE 是否存在且為一個連結檔?if[ -L $FILE ]; then

2. 關於檔案的權限偵測,如 -r $FILE 表示可讀否 (但 root 權限常有例外)
標誌意義範例
-r偵測該檔名是否存在且具有『可讀』的權限?if[ -r $FILE ]; then
-w偵測該檔名是否存在且具有『可寫』的權限?if[ -w $FILE ]; then
-x偵測該檔名是否存在且具有『可執行』的權限?if[ -x $FILE ]; then
-u偵測該檔名是否存在且具有『SUID』的屬性?if[ -u $FILE ]; then
-g偵測該檔名是否存在且具有『SGID』的屬性?if[ -g $FILE ]; then
-k偵測該檔名是否存在且具有『Sticky bit』的屬性?if[ -k $FILE ]; then
-s偵測該檔名是否存在且為『非空白檔案』?if[ -s $FILE ]; then

3. 兩個檔案之間的比較
標誌意義範例
-nt(newer than)判斷 $FILE1 是否比 $FILE2 新if[ $FILE1 -nt $FILE2 ]; then
-ot(older than)判斷 $FILE1 是否比 $FILE2 舊if[ $FILE1 -ot $FILE2 ]; then
-ef判斷 $FILE1 與 $FILE2 是否為同一檔案,
可用在判斷 hard link 的判定上。
主要意義在判定,兩個檔案是否均指向同一個 inode 哩!
if[ $FILE1 -ef $FILE2 ]; then

4. 關於兩個整數之間的判定
標誌意義範例
-eq兩數值相等 (equal)if[ n1 -eq n2 ]; then
-ne兩數值不等 (not equal)if[ n1 -ne n2 ]; then
-gtn1 大於 n2 (greater than)if[ n1 -gt n2 ]; then
-ltn1 小於 n2 (less than)if[ n1 -lt n2 ]; then
-gen1 大於等於 n2 (greater than or equal)if[ n1 -ge n2 ]; then
-len1 小於等於 n2 (less than or equal)if[ n1 -le n2 ]; then

5. 判定字串的資料
標誌意義範例
-z判定字串是否為 0 ?若 $STR 為空字串,則為 trueif[ -z $STR ]; then
-n判定字串是否非為 0 ?若 $STR 為空字串,則為 false。
註: -n 亦可省略
if[ -n $STR ]; then
=判定 $STR1 是否等於 $STR2 ,若相等,則回傳 trueif[ $STR1 = $STR2 ]; then
!=判定 $STR1 是否不等於 $STR2 ,若相等,則回傳 falseif[ $STR1 != $STR2 ]; then

6. 多重條件判定
標誌意義範例
-a(and)兩狀況同時成立if[ -r $FILE -a -x $FILE ]; then
-o(or)兩狀況任何一個成立if[ -r $FILE -o -x $FILE ]; then
!反相狀態if[ ! -x $FILE ]; then

0 回應: