目錄
在 Shell 編程中,文件測試運算符使用的很廣泛,經常需要檢測一個文件的屬性,下面結合實例進行說明。
一、文件測試運算符
操作符 | 說明 |
---|---|
-b file | 檢測文件是否是塊設備文件,如果是,則返回 true。 |
-c file | 檢測文件是否是字符設備文件,如果是,則返回 true。 |
-d file | 檢測文件是否是目錄,如果是,則返回 true。 |
-f file | 檢測文件是否是普通文件(既不是目錄,也不是設備文件),如果是,則返回 true。 |
-g file | 檢測文件是否設置了 SGID 位,如果是,則返回 true。 |
-u file | 檢測文件是否設置了 SUID 位,如果是,則返回 true。 |
-k file | 檢測文件是否設置了粘着位(Sticky Bit),如果是,則返回 true。 |
-p file | 檢測文件是否是有名管道,如果是,則返回 true。 |
-r file | 檢測文件是否可讀,如果是,則返回 true。 |
-w file | 檢測文件是否可寫,如果是,則返回 true。 |
-x file | 檢測文件是否可執行,如果是,則返回 true。 |
-s file | 檢測文件是否爲空(文件大小是否大於0),不爲空返回 true。 |
-e file | 檢測文件(包括目錄)是否存在,如果是,則返回 true。 |
二、常用實例
2.1 -d file 檢測目錄
#!/bin/bash
file="/root"
if [ -d $file ]
then
echo "$file is directory!"
else
echo "$file is not directory!"
fi
輸出:
[root@localhost Shell]# ./dir.sh
/root is directory!
[root@localhost Shell]#
2.2 -f file 檢測普通文件
#!/bin/bash
file="/root/regularFile"
if [ -f $file ]
then
echo "$file is regular file!"
else
echo "$file is not regular file!"
fi
輸出:
[root@localhost Shell]# ./dir.sh
/root/regularFile is regular file!
[root@localhost Shell]#
2.3 -x file 檢測文件可執行
#!/bin/bash
file="/root/Shell/dir.sh"
if [ -x $file ]
then
echo "$file is executable file!"
else
echo "$file is not executable file!"
fi
輸出:
[root@localhost Shell]# ls -l dir.sh
-rwxr-xr-x. 1 root root 145 2月 6 10:54 dir.sh
[root@localhost Shell]# ./dir.sh
/root/Shell/dir.sh is executable file!
[root@localhost Shell]#
2.4 -e file 檢測文件/目錄存在
#!/bin/bash
file="/root"
if [ -e $file ]
then
echo "$file is exist!"
else
echo "$file is not exist!"
fi
輸出:
[root@localhost Shell]# ./dir.sh
/root is exist!
[root@localhost Shell]#
2.5 -b file 檢測塊設備文件
#!/bin/bash
if [ -b /dev/sda ]
then
echo "/dev/sda is Block Device File!"
else
echo "/dev/sda is not Block Device File!"
fi
輸出爲:
[root@localhost Shell]# ./dir.sh
/dev/sda is Block Device File!
[root@localhost Shell]#
三、總結
文件測試運算符在 Shell 編程中經常使用,幾個常用的運算符要記住。
參考文獻: