在进行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 filepath | file exists. all files type |
| -b filepath | file exists and is a block special file. |
| -c filepath | file exists and is a character special file. |
| -d filepath | file exists and is a directory. |
| -e filepath | file exists (等同于 -a). |
| -f filepath | file exists and is a regular file. |
| -g filepath | file exists and has its setgid(2) bit set. |
| -G filepath | file exists and has the same group ID as this process. |
| -k filepath | file exists and has its sticky bit set. |
| -L filepath | file exists and is a symbolic link. |
| -n filepath | string length is not zero. |
| -o filepath | Named option is set on. |
| -O filepath | file exists and is owned by the user ID of this process. |
| -p filepath | file exists and is a first in, first out (FIFO) special file or named pipe. |
| -r filepath | file exists and is readable by the current process. |
| -s filepath | file exists and has a size greater than zero. |
| -S filepath | file exists and is a socket. |
| -t filepath | file descriptor number fildes is open and associated with a terminal device. |
| -u filepath | file exists and has its setuid(2) bit set. |
| -w filepath | file exists and is writable by the current process. |
| -x filepath | file exists and is executable by the current process. |

本文介绍了如何在Linux shell脚本中使用if语句判断文件和目录的存在,并列举了多种文件类型测试选项。掌握这些技巧有助于高效开发应用程序。

1万+

被折叠的 条评论
为什么被折叠?



