在进行linux系统相关应用程序开发时,少不了要书写一些shell脚本,有时候要用到判断文件或者目录是否存在的脚本,本文笔者做一下笔记,已备后查。

shell判断文件是否存在的脚本如下:

# [ 与 ] 的前后必须有空格符
if [ -f /path/file.ext ] 
then 
     echo "The file exist"
else
     echo "The file doesn't exist"
fi

# 判断某链接是否存在
if [ -L /path/link ] 
then 
    echo "The link exist"
else
    echo "The link doesn't exist"
fi

 其实shell对于文件册测试有好几种选项开关,现在例举如下:

表达式测试含义
-a filepathfile exists. all files type
-b filepathfile exists and is a block special file.
-c filepathfile exists and is a character special file.
-d filepathfile exists and is a directory.
-e filepathfile exists (等同于 -a).
-f  filepathfile exists and is a regular file.
-g filepathfile exists and has its setgid(2) bit set.
-G filepathfile exists and has the same group ID as this process.
-k filepathfile exists and has its sticky bit set.
-L filepathfile exists and is a symbolic link.
-n filepathstring length is not zero.
-o filepathNamed option is set on.
-O filepathfile exists and is owned by the user ID of this process.
-p filepathfile exists and is a first in, first out (FIFO) special file or
named pipe.
-r filepathfile exists and is readable by the current process.
-s filepathfile exists and has a size greater than zero.
-S filepathfile exists and is a socket.
-t filepathfile descriptor number fildes is open and associated with a
terminal device.
-u filepathfile exists and has its setuid(2) bit set.
-w filepathfile exists and is writable by the current process.
-x filepathfile exists and is executable by the current process.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐