Reputation: 33
I need to create script that goes like this:
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
My problem is that when I try
if [ -f naz* ]
I end up with
bash: [: too many arguments
because there are more than 1 files that meet the criteria. I'm looking for a solution that would work with multiple files found.
Upvotes: 3
Views: 70
Reputation: 185179
You can't use [
test like this on multiple files.
Better do:
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
Upvotes: 3
Reputation: 2676
This solution might take a while to evaluate in a directory with a large number of files but is more succinct
if [ `find . -name "naz*" -type f -d 1 | wc -l` -ge 1 ]
If you want to travel to subdirectories you can do so by removing the -d 1
part.
Upvotes: 0