File Test Operators
File test operators are used to detect various properties of Unix files.
Attribute detection is described as follows:
operator |
Description |
Example |
-B File |
Detects if the file is a block device file, and returns True if it is. |
[-B $file] returns FALSE. |
-C file |
Detects if the file is a character device file, and returns True if it is. |
[-C $file] returns false. |
-D File |
Detects if the file is a directory, and returns True if it is. |
[-D $file] returns false. |
-F File |
Detects if the file is a normal file (neither a directory nor a device file), and returns True if it is. |
[-F $file] returns TRUE. |
-G file |
Detects if the file has a SGID bit set, and returns True if it is. |
[-G $file] returns false. |
-K File |
Detects if the file has a sticky bit set (Sticky bit), and returns True if it is. |
[-K $file] returns false. |
-P File |
Detects if the file is a well-known pipe, and returns True if it is. |
[-P $file] returns false. |
-U file |
Detects if the file has a SUID bit set, and returns True if it is. |
[-U $file] returns false. |
-R File |
Detects if the file is readable and returns true if it is. |
[-R $file] returns TRUE. |
-W File |
Detects if the file is writable and returns true if it is. |
[-W $file] returns TRUE. |
-X File |
Detects if the file can be executed and, if so, returns True. |
[-X $file] returns TRUE. |
-S file |
Detects whether the file is empty (the file size is greater than 0) and does not return true for null. |
[-S $file] returns TRUE. |
-E File |
Detects whether the file (including the directory) exists and, if so, returns True. |
[-e $file] returns TRUE. |
Instance
The file "test.sh", which has a size of 100 bytes, has rwx permissions. The following code will detect various properties of the file:
#!/bin/bashfile="test.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
Reference from "Rookie Tutorial"
Shell File Test Operators