Warm tip: This article is reproduced from serverfault.com, please click

sh-检查Shell脚本中是否存在带通配符的文件

(sh - Check if a file exists with wildcard in shell script)

发布于 2011-06-15 19:50:26

我正在尝试检查文件是否存在,但是带有通配符。这是我的示例:

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

我也尝试过不使用双引号。

Questioner
Danny
Viewed
0
18.5k 2020-10-15 06:13:47

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

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

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

来源


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

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

我重定向了ls输出,使其完全静音。


编辑:由于此答案引起了关注(并且评论家的评论非常有用,为评论),因此,这是一种优化,它也依赖于glob扩展,但是避免了使用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的答案非常相似,但是它避免了整个列表的不必要迭代。