Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if multiple files exist

Tags:

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

like image 357
stefcud Avatar asked Feb 08 '13 04:02

stefcud


2 Answers

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 
like image 199
tdu Avatar answered Nov 09 '22 12:11

tdu


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.

like image 20
Hui Zheng Avatar answered Nov 09 '22 12:11

Hui Zheng