Test if multiple files exist

2020-08-10 07:19发布

How can i use test command for arbitrary number of files, passed in argument by regexp

for example:

test -f /var/log/apache2/access.log.* && echo "exists one or more files"

but mow print error: bash: test: too many arguments

标签: bash
10条回答
何必那么认真
2楼-- · 2020-08-10 07:58

Or using find

if [ $(find /var/log/apache2/ -type f -name "access.log.*" | wc -l) -gt 0 ]; then
  echo "ok"
else
  echo "ko"
fi
查看更多
我命由我不由天
3楼-- · 2020-08-10 08:01

To avoid "too many arguments error", you need xargs. Unfortunately, test -f doesn't support multiple files. The following one-liner should work:

for i in /var/log/apache2/access.log.*; do test -f "$i" && echo "exists one or more files" && break; done

BTW, /var/log/apache2/access.log.* is called shell-globbing, not regexp, please check this: Confusion with shell-globbing wildcards and Regex.

查看更多
相关推荐>>
4楼-- · 2020-08-10 08:01

This solution seems to me more intuitive:

if [ `ls -1 /var/log/apache2/access.log.* 2>/dev/null | wc -l ` -gt 0 ];
then
    echo "ok"
else
    echo "ko"
fi
查看更多
成全新的幸福
5楼-- · 2020-08-10 08:02

You just need to test if ls has something to list:

ls /var/log/apache2/access.log.* >/dev/null 2>&1 && echo "exists one or more files"
查看更多
一夜七次
6楼-- · 2020-08-10 08:03
ls -1 /var/log/apache2/access.log.* | grep . && echo "One or more files exist."
查看更多
趁早两清
7楼-- · 2020-08-10 08:03

more simplyfied:

if ls /var/log/apache2/access.log.* 2>/dev/null 1>&2; then
   echo "ok"
else
   echo "ko"
fi
查看更多
登录 后发表回答