在bash中检查是否至少存在一个文件

3

我有这个

if [[ -e file.jpg ]] ;then echo "aaaaaaaaa"; fi

它会打印出 "aaaaaaa"。

但是我想要打印出是否存在 file.png 或者 file.jpg。

所以我需要像这样的东西:

if [[ -e file.* ]] ;then echo "aaaaaaaaa"; fi

但它不起作用,语法中缺少某些东西。
谢谢。

"at least" - musefan
可能是重复的问题:在bash中测试glob是否有任何匹配项 - Shawn Chin
2个回答

10
如果您启用bash的nullglob设置,则模式file.*将会在没有这样的文件时扩展为空字符串:
shopt -s nullglob
files=(file.*)
# now check the size of the array
if (( ${#files[@]} == 0 )); then
    echo "no such files"
else
    echo "at least one:"
    printf "aaaaaaaaa %s\n" "${files[@]}"
fi

如果您不启用nullglob,那么files=(file.*)将导致一个数组只有一个元素,即字符串"file.*"。

2
为什么不使用循环?
for i in file.*; do
   if [[ -e $i ]]; then
      # exists...
   fi
done

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接