检查 shell 脚本中是否存在带有通配符的文件 [英] Check if a file exists with a wildcard in a shell script
问题描述
我正在尝试检查文件是否存在,但使用通配符.这是我的例子:
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 脚本,最直接、最高效的方法是:
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.
这里的优化也依赖于 glob 扩展,但避免使用 ls
:
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屋!