You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Bash中[[ -f 目录/*.png ]]判断始终返回false?

Bash判断目录中是否存在PNG文件的问题解决

问题场景

我有一个包含2个PNG文件的目录:

% ls test_folder
1.png 2.png

列出目录中的所有PNG文件可正常执行:

% echo test_folder/*.png
test_folder/1.png test_folder/2.png

但判断目录中是否存在PNG文件时始终返回false:

% if [[ -f test_folder/*.png ]]; then echo 'found'; else echo 'not found'; fi
not found

我参考了相关指南,但不知问题出在哪里。请原谅我对Bash的了解有限。

问题原因

[[ -f ]] 只能检查单个文件是否为普通文件。当test_folder/*.png匹配到多个文件时,表达式会被展开为[[ -f test_folder/1.png test_folder/2.png ]],这不符合-f的语法规则,因此条件判断会失败并返回false。

正确的解决方法

方法1:利用数组存储匹配结果

开启nullglob选项后,无匹配时通配符会展开为空字符串,通过判断数组长度即可知道是否存在匹配文件:

shopt -s nullglob
files=(test_folder/*.png)
if [[ ${#files[@]} -gt 0 ]]; then
    echo 'found'
else
    echo 'not found'
fi
shopt -u nullglob  # 可选:恢复默认设置,避免影响后续命令

方法2:通过ls命令的执行状态判断

利用ls的返回值,同时将输出和错误信息重定向到/dev/null,避免冗余输出:

if ls test_folder/*.png >/dev/null 2>&1; then
    echo 'found'
else
    echo 'not found'
fi

方法3:使用find命令精确查找

通过find指定查找深度和文件名模式,配合grep -q判断是否有结果:

if find test_folder -maxdepth 1 -type f -name "*.png" | grep -q .; then
    echo 'found'
else
    echo 'not found'
fi

内容的提问来源于stack exchange,提问作者Hendra Anggrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:06:23