
- Unix/Linux 初學者指南
- Unix/Linux - 首頁
- Unix/Linux - 什麼是Linux?
- Unix/Linux - 入門
- Unix/Linux - 檔案管理
- Unix/Linux - 目錄
- Unix/Linux - 檔案許可權
- Unix/Linux - 環境
- Unix/Linux - 基本工具
- Unix/Linux - 管道與過濾器
- Unix/Linux - 程序
- Unix/Linux - 通訊
- Unix/Linux - vi 編輯器
- Unix/Linux Shell程式設計
- Unix/Linux - Shell 指令碼
- Unix/Linux - 什麼是Shell?
- Unix/Linux - 使用變數
- Unix/Linux - 特殊變數
- Unix/Linux - 使用陣列
- Unix/Linux - 基本運算子
- Unix/Linux - 決策制定
- Unix/Linux - Shell 迴圈
- Unix/Linux - 迴圈控制
- Unix/Linux - Shell 替換
- Unix/Linux - 引號機制
- Unix/Linux - I/O 重定向
- Unix/Linux - Shell 函式
- Unix/Linux - 手冊頁幫助
- 高階 Unix/Linux
- Unix/Linux - 標準 I/O 流
- Unix/Linux - 檔案連結
- Unix/Linux - 正則表示式
- Unix/Linux - 檔案系統基礎
- Unix/Linux - 使用者管理
- Unix/Linux - 系統性能
- Unix/Linux - 系統日誌
- Unix/Linux - 訊號和陷阱
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
廣告