Unix/Linux - Shell 檔案測試運算子示例



我們有一些運算子可以用來測試與Unix檔案相關的各種屬性。

假設變數file包含一個現有檔名"test",大小為100位元組,並且具有執行許可權:

運算子 描述 示例
-b file 檢查檔案是否為塊特殊檔案;如果是,則條件為真。 [ -b $file ] 為假。
-c file 檢查檔案是否為字元特殊檔案;如果是,則條件為真。 [ -c $file ] 為假。
-d file 檢查檔案是否為目錄;如果是,則條件為真。 [ -d $file ] 為假。
-f file 檢查檔案是否為普通檔案(相對於目錄或特殊檔案);如果是,則條件為真。 [ -f $file ] 為真。
-g file 檢查檔案是否設定了其設定組ID (SGID) 位;如果是,則條件為真。 [ -g $file ] 為假。
-k file 檢查檔案是否設定了其粘滯位;如果是,則條件為真。 [ -k $file ] 為假。
-p file 檢查檔案是否為命名管道;如果是,則條件為真。 [ -p $file ] 為假。
-t file 檢查檔案描述符是否已開啟並與終端關聯;如果是,則條件為真。 [ -t $file ] 為假。
-u file 檢查檔案是否設定了其設定使用者ID (SUID) 位;如果是,則條件為真。 [ -u $file ] 為假。
-r file 檢查檔案是否可讀;如果是,則條件為真。 [ -r $file ] 為真。
-w file 檢查檔案是否可寫;如果是,則條件為真。 [ -w $file ] 為真。
-x file 檢查檔案是否可執行;如果是,則條件為真。 [ -x $file ] 為真。
-s file 檢查檔案大小是否大於 0;如果是,則條件為真。 [ -s $file ] 為真。
-e file 檢查檔案是否存在;即使檔案是目錄但存在,也為真。 [ -e $file ] 為真。

示例

以下示例使用了所有檔案測試運算子:

假設變數 file 包含現有檔名"/var/www/tutorialspoint/unix/test.sh",大小為 100 位元組,並且具有執行許可權:

#!/bin/sh

file="/var/www/tutorialspoint/unix/test.sh"

if [ -r $file ]
then
   echo "File has read access"
else
   echo "File does not have read access"
fi

if [ -w $file ]
then
   echo "File has write permission"
else
   echo "File does not have write permission"
fi

if [ -x $file ]
then
   echo "File has execute permission"
else
   echo "File does not have execute permission"
fi

if [ -f $file ]
then
   echo "File is an ordinary file"
else
   echo "This is sepcial file"
fi

if [ -d $file ]
then
   echo "File is a directory"
else
   echo "This is not a directory"
fi

if [ -s $file ]
then
   echo "File size is not zero"
else
   echo "File size is zero"
fi

if [ -e $file ]
then
   echo "File exists"
else
   echo "File does not exist"
fi

上述指令碼將產生以下結果:

File does not have write permission
File does not have execute permission
This is sepcial file
This is not a directory
File size is not zero
File does not exist

使用檔案測試運算子時,需要注意以下幾點:

  • 運算子和表示式之間必須有空格。例如,2+2 是不正確的;應寫成 2 + 2。

  • if...then...else...fi 語句是決策語句,將在下一章中解釋。

unix-basic-operators.htm
廣告