且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查shell脚本中是否存在带有通配符的文件

更新时间:2023-11-25 22:00:34

更新:对于 bash 脚本,最直接和高效的方法是:

Update: For bash scripts, the most direct and performant approach is:

if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
    echo "pattern exists!"
fi

即使在包含数百万个文件的目录中也能非常快速地工作,并且不涉及新的子 shell.

This will work very speedily even in directories with millions of files and does not involve a new subshell.

来源

最简单的应该是依赖 ls 返回值(当文件不存在时返回非零值):

The simplest should be to rely on ls return value (it returns non-zero when the files do not exist):

if ls /path/to/your/files* 1> /dev/null 2>&1; then
    echo "files do exist"
else
    echo "files do not exist"
fi

我重定向了 ls 输出以使其完全静音.

I redirected the ls output to make it completely silent.

由于这个答案得到了一些关注(以及作为评论非常有用的评论家评论),这里有一个优化也依赖于全局扩展,但避免使用 ls:

Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls:

for f in /path/to/your/files*; do

    ## Check if the glob gets expanded to existing files.
    ## If not, f here will be exactly the pattern above
    ## and the exists test will evaluate to false.
    [ -e "$f" ] && echo "files do exist" || echo "files do not exist"

    ## This is all we needed to know, so we can break after the first iteration
    break
done

这与@grok12 的答案非常相似,但它避免了对整个列表进行不必要的迭代.

This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.