检查一个目录中是否存在1个或多个特定文件?

3

我需要创建一个脚本,其内容如下:

if directory contains atleast one file (1 or more) that starts with 'naz'
    #do something
else (contains 0 files that start with 'naz')
    #do something else

我的问题是,当我尝试时

if [ -f naz* ]

我最终遇到了

bash: [: 参数太多

因为符合条件的文件超过了1个。我正在寻找适用于找到多个文件的解决方案。

2个回答

3

你不能在多个文件上像这样使用[ test。

最好这样做:

shopt -s nullglob
compgen -W naz* &>/dev/null
case $? in
    0) echo "only one file match" ;;
    1) echo "more than one file match" ;;
    2) echo "no file match" ;;
esac

0

这个解决方案在包含大量文件的目录中可能需要一些时间来评估,但更加简洁。

if [ `find . -name "naz*" -type f -d 1 | wc -l` -ge 1 ]

如果你想进入子目录,可以删除-d 1这部分。


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