13

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?

3 Answers 3

17

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

2
  • 1
    I added -maxdepth 1 to only count files in the current directory Jun 7, 2011 at 17:23
  • 1
    You probably want to quote '*.zip' in case there are any .zip files in the current directory when this is invoked, in which case the shell will have expanded the *.zip for you, while you want it passed through to find(1).
    – Phil P
    Jun 7, 2011 at 17:50
4

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.)

6
  • As an alternative, you could also do count=$(find /import -type f -name "*.zip" | wc -l)
    – slillibri
    Jun 7, 2011 at 17:12
  • sure, but that has a different meaning to just ls /import/*.zip if there are subdirectories
    – Mat
    Jun 7, 2011 at 17:14
  • I set the maxdepth to avoid counting files in subdirectories and updated the script to use -gt. Thanks for the help Jun 7, 2011 at 17:27
  • This fails if there are too many files in the directory to fit in argv for the ls invocation.
    – Phil P
    Jun 7, 2011 at 17:49
  • Ah, right. Corrected with a find variant.
    – Mat
    Jun 7, 2011 at 17:55
0

I tried your script and, as expected, when no files are matched it does show 0 files in the output, but also shows the ls error just before. Solving this is quite easy, there's no need to ditch ls. Just replace the first line with this:

count=$(ls /import/*.zip 2>/dev/null| wc -l)

2>/dev/null redirects stderr to /dev/null, suppressing the error message.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .