檔案測試運算子用於檢測 unix 檔案的各種屬性。
屬性檢測描述如下:操作符 說明 舉例
-b file 檢測檔案是否是塊裝置檔案,如果是,則返回 true。 [ -b $file ] 返回 false。
-c file 檢測檔案是否是字元裝置檔案,如果是,則返回 true。 [ -c $file ] 返回 false。
-d file 檢測檔案是否是目錄,如果是,則返回 true。 [ -d $file ] 返回 false。
-f file 檢測檔案是否是普通檔案(既不是目錄,也不是裝置檔案),如果是,則返回 true。 [ -f $file ] 返回 true。
-g file 檢測檔案是否設定了 sgid 位,如果是,則返回 true。 [ -g $file ] 返回 false。
-k file 檢測檔案是否設定了粘著位(sticky bit),如果是,則返回 true。 [ -k $file ] 返回 false。
-p file 檢測檔案是否是具名管道,如果是,則返回 true。 [ -p $file ] 返回 false。
-u file 檢測檔案是否設定了 suid 位,如果是,則返回 true。 [ -u $file ] 返回 false。
-r file 檢測檔案是否可讀,如果是,則返回 true。 [ -r $file ] 返回 true。
-w file 檢測檔案是否可寫,如果是,則返回 true。 [ -w $file ] 返回 true。
-x file 檢測檔案是否可執行,如果是,則返回 true。 [ -x $file ] 返回 true。
-s file 檢測檔案是否為空(檔案大小是否大於0),不為空返回 true。 [ -s $file ] 返回 true。
-e file 檢測檔案(包括目錄)是否存在,如果是,則返回 true。 [ -e $file ] 返回 true。
例項變數 file 表示檔案"/home/shell/first.sh",它的大小為100位元組,具有 rwx 許可權。下面的**,將檢測該檔案的各種屬性:
#!/bin/bash
file="/home/shell/first.sh"
if [ -r $file ]
then
echo "檔案可讀"
else
echo "檔案不可讀"
fiif [ -w $file ]
then
echo "檔案可寫"
else
echo "檔案不可寫"
fiif [ -x $file ]
then
echo "檔案可執行"
else
echo "檔案不可執行"
fiif [ -f $file ]
then
echo "檔案為普通檔案"
else
echo "檔案為特殊檔案"
fiif [ -d $file ]
then
echo "檔案是個目錄"
else
echo "檔案不是個目錄"
fiif [ -s $file ]
then
echo "檔案不為空"
else
echo "檔案為空"
fiif [ -e $file ]
then
echo "檔案存在"
else
echo "檔案不存在"
fi
執行指令碼,輸出結果如下所示:檔案可讀
檔案可寫
檔案可執行
檔案為普通檔案
檔案不是個目錄
檔案不為空
檔案存在
shell 檔案測試運算子
檔案測試運算子用於檢測 unix 檔案的各種屬性。操作符說明 舉例 b file 檢測檔案是否是塊裝置檔案,如果是,則返回 true。b file 返回 false。c file 檢測檔案是否是字元裝置檔案,如果是,則返回 true。c file 返回 false。d file 檢測檔案是否是目錄,...
shell 測試檔案狀態運算子
測試命令 test,詳細可用man test查詢 測試符號 注意只有一層中括號,中括號內左右兩側必須要有空格 test與效果都一樣,引數也都一樣1.test和引數解釋 d 目錄 s 檔案長度 0 非空 f 正規檔案 w 當前使用者可寫 root使用者無視許可權 r 可讀 x 可執行 l 軟連線檔案 ...
Shell 基本運算子
好久沒用過shell了,最近複習下。扣了幾張老大部落格的圖嘿嘿.shell 和其他程式語言一樣,支援多種運算子,包括 原生bash不支援簡單的數 算,但是可以通過其他命令來實現,例如 awk 和 expr,expr 最常用。expr 是一款表示式計算工具,使用它能完成表示式的求值操作。示例 root...