我们可以有/tmp/file.1
或/tmp/file.43.434
或/tmp/file-hegfegf
等等
那么我们如何在 bash 中验证是否/tmp/file*
存在呢?
我们尝试作为
[[ -f "/tmp/file*" ]] && echo "file exists"
但上面不起作用
如何修复它?
答案1
我将使用find
或for
循环来识别这种情况。
示例#1 find
(使用 GNU 扩展来限制搜索空间):
# First try with no matching files
[ -n "$(find /tmp/file* -maxdepth 1 -type f -print -quit)" ] && echo yes || echo no # "no"
# Create some matching files and try the same command once more
touch /tmp/file.1 /tmp/file.43.434 /tmp/file-hegfegf
[ -n "$(find /tmp/file* -maxdepth 1 -type f -print -quit)" ] && echo yes || echo no # "yes"
示例 #2 带for
循环
found=
for file in /tmp/file*
do
[ -f "$file" ] && found=yes && break
done
[ yes = "$found" ] && echo yes || echo no # No files "no", otherwise "yes"