检查shell脚本中是否存在带有通配符的文件 [英] Check if a file exists with wildcard in shell script

查看:108
本文介绍了检查shell脚本中是否存在带有通配符的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查文件是否存在,但使用了通配符.这是我的例子:

I'm trying to check if a file exists, but with a wildcard. Here is my example:

if [ -f "xorg-x11-fonts*" ]; then
    printf "BLAH"
fi

我也试过没有双引号.

推荐答案

更新:对于 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.

这篇关于检查shell脚本中是否存在带有通配符的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆