一、文件测试运算符
-d file 检测文件是否是目录,如果是,则返回 true。 [ -d $file ] 返回 false。 -f file 检测文件是否是普通文件(既不是目录,也不是设备文件),如果是,则返回 true。 [ -f $file ] 返回 true。 -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_PATH=/xx/xx/xxx.log
if [ -f "$FILE_PATH" ];then
echo "$FILE_PATH 存在"
else
echo "$FILE_PATH 不存在"
fi
三、判断文件是否存在,以及是否具有可执行权限
FILE_PATH=/xx/xx/xxx.log
if [ -x "$FILE_PATH" ];then
echo "$FILE_PATH 文件存在"
else
FILE $FILE_PATH
fi
四、判断目录是否存在
FILE_PATH=/xx/xx
if [ -d "$FILE_PATH" ];then
echo "$FILE_PATH 存在"
else
echo "$FILE_PATH 不存在"
fi
五、判断变量是否有值
if [ -n "$1" ];then
echo "存在"
else
echo "不存在"
fi
六、以下是一些不是很常用的判断
Conditional Logic on Files
-a file exists.
-b file exists and is a block special file.
-c file exists and is a character special file.
-d file exists and is a directory.
-e file exists (just the same as -a).
-f file exists and is a regular file.
-g file exists and has its setgid(2) bit set.
-G file exists and has the same group ID as this process.
-k file exists and has its sticky bit set.
-L file exists and is a symbolic link.
-n string length is not zero.
-o Named option is set on.
-O file exists and is owned by the user ID of this process.
-p file exists and is a first in, first out (FIFO) special file or named pipe.
-r file exists and is readable by the current process.
-s file exists and has a size greater than zero.
-S file exists and is a socket.
-t file descriptor number fildes is open and associated with a terminal device.
-u file exists and has its setuid(2) bit set.
-w file exists and is writable by the current process.
-x file exists and is executable by the current process.
-z string length is zero.