视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
使用BashShell检查文件是否存在的方法
2020-11-27 14:27:05 责编:小采
文档


前言

大家在工作的时候可能经常会遇到这样的需求,在类Unix系统的Bash环境下,怎样检查文件是否存在呢?既然有需求,当然就有解决的办法了,Shell中的test命令,可以用来检测文件的类型或者比较数值是否相等,该命令也能用来检查文件是否存在。

可以用如下的命令来进行检查:

test -e filename
[ -e filename ]
 
test -f filename
[ -f filename ]

下面的命令,则使用Shell的条件表达式,判断/etc/hosts文件是否存在:

[ -f /etc/hosts ] && echo "Found" || echo "Not found"

该组合命令会输出以下内容:

Found

更常见的用法,则是将test命令放置在if..else..fi条件判断的条件表达式,然后在其中写上不同的分支逻辑

#!/bin/bash
file="/etc/hosts"
if [ -f "$file" ]
then
 echo "$file found."
else
 echo "$file not found."
fi

检测文件属性的相关操作符

如果文件存在,并且具有相应的属性,如下的操作符都会返回true:

-b FILE
 FILE exists and is block special
-c FILE
 FILE exists and is character special
-d FILE
 FILE exists and is a directory
-e FILE
 FILE exists
-f FILE
 FILE exists and is a regular file
-g FILE
 FILE exists and is set-group-ID
-G FILE
 FILE exists and is owned by the effective group ID
-h FILE
 FILE exists and is a symbolic link (same as -L)
-k FILE
 FILE exists and has its sticky bit set
-L FILE
 FILE exists and is a symbolic link (same as -h)
-O FILE
 FILE exists and is owned by the effective user ID
-p FILE
 FILE exists and is a named pipe
-r FILE
 FILE exists and read permission is granted
-s FILE
 FILE exists and has a size greater than zero
-S FILE
 FILE exists and is a socket
-t FD file descriptor FD is opened on a terminal
-u FILE
 FILE exists and its set-user-ID bit is set
-w FILE
 FILE exists and write permission is granted
-x FILE
 FILE exists and execute (or search) permission is granted

以上命令,从man test复制而来。

使用上述符号的方法一模一样:

if [ operator FileName ]
then
 echo "FileName - Found, take some action here"
else
 echo "FileName - Not found, take some action here"
fi

总结

下载本文
显示全文
专题