Linux Shell 上检查文件是否存在

大家在工作的时候可能经常会遇到这样的需求,在类 Unix 系统的 bash 环境下,怎样检查文件是否存在呢?既然有需求,当然就有解决的办法了。

Shell 中的 test 命令可以用来检测文件的类型或者比较数值是否相等,该命令也能用来检查文件是否存在,具体如下所示:

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

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

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

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

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

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

Found

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

如果文件存在,并且具有相应的属性,如下的操作符都会返回 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

还有两个文件之间相互比较的三个表达式:

       FILE1 -ef FILE2
              FILE1 and FILE2 have the same device and inode numbers

       FILE1 -nt FILE2
              FILE1 is newer (modification date) than FILE2

       FILE1 -ot FILE2
              FILE1 is older than FILE2
打赏作者
这里是 “ CCIE 工程师社区 ” 官方的捐款通道,您是否可以考虑请我们喝杯咖啡呢?

您的支持将鼓励我们继续创作!

[微信] 扫描二维码打赏

[支付宝] 扫描二维码打赏

Was this article helpful?

Related Articles

Leave A Comment?

This site uses Akismet to reduce spam. Learn how your comment data is processed.