Bash script to count number of files

I have a script and I want to display different messages if a file exists or not. I have a script like:

count=ls /import/*.zip | wc -l

echo "Number of files: " $count
if [ "$count" > "0" ]; then
    echo "Import $count files"
else
    echo "**** No files found ****"
fi

However, if no files exist, this is showing No such file or directory instead of 0 files. There is a directory in the /import/ directory, so I can't just do a ls command as that will always return a value greater than 0.

How can I count the number of files of a specific extension (.zip, .gz, etc.) and use that value in a bash script to both display the number of files and then use it in an if statement to display different messages?


Solution 1:

count=$(find /import -maxdepth 1 -name '*.zip' | wc -l)

Solution 2:

Try with this:

count=$(find /import/ -maxdepth 1 -type f -name '*.zip' | wc -l)
...
if [ $count -gt 0 ] ; then
  ...
else
  ...
fi

The idea is to hide the "no such file" error that gets printed to STDERR by sending it to the bitbucket, and to use the proper test function for comparing numbers. (-gt stands for "greater than". There's also -eq, -lt, -ge, etc.)