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?

Wallace Sean
  • 137
  • 1
  • 1
  • 6

3 Answers3

17

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

Chris Ting
  • 899
  • 4
  • 5
  • 1
    I added -maxdepth 1 to only count files in the current directory – Wallace Sean Jun 07 '11 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 07 '11 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.)

Mat
  • 1,536
  • 1
  • 17
  • 21
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.

Eduardo Ivanec
  • 14,881
  • 1
  • 37
  • 43