Atomiklan
Atomiklan

Reputation: 5464

Counting files in directory

For some reason I seem to be having some formatting issues here. I'm trying to count the number of files in a jvm directory. I'm counting to compare against a known integer (ie the file should contain 51 files). The purpose is to make sure all the files are present. Basically it was a quick and dirty way to see if all files were present after download and un-tar as part of an installer. Originally I was going to use MD5 (which in some ways is more ideal as it will check for file corruption), but it will take too long and I cant take an MD5 of a directory so I was either have to retar the directory in question before calculating or caluclate each file which is just getting too cumbersome. I cant use diff either as there is no identical directory to compare against yet. All it is doing is checking that all the required files are present before beginning install. If someone can recommend a different strategy, I am open ears. If not, this simple solution will work if I get it working correctly. Here is all I did:

First find the number of files in the jvm folder (should always be 51 as we provide the jvm container)

COUNT=$(find jvm -type f | wc -l)
if [ "$COUNT" = "51" ]; then
  YAY
else
  OOPS
fi

For some reason, I think the output of the first command contains whitespace and as a result is storing all of it as a string. When the compare occurs, it fails.

This script must run in both bash and sh

Upvotes: 0

Views: 165

Answers (3)

clt60
clt60

Reputation: 63974

You can use also the simple:

count=`find jvm -maxdepth 1 -type f -print0 | grep -zc '.'`
  • the find
    • search for all files in the jvm directory
    • and print them as null terminated strings.
  • the grep
    • the -z says grep to accept null terminated strings as input (each such string is one "line")
    • the -c counts the matchd "lines"
    • match for any character .
  • the backticks are bash and sh compatible
  • the script is immune to any special character in the filename (e.g. can contain \n too)

With this you can also filter&count filenames, like

count=`find jvm -maxdepth 1 -type f -print0 | grep -zc '\.java'`

to count files ending with .java and such.

Upvotes: 0

David W.
David W.

Reputation: 107090

You're doing a string comparison:

if [ "$COUNT" = "51" ]

Since $count is a number, do a numeric comparison instead with -eq:

if [[ $COUNT -eq 51 ]]

This way, the white space in front of $COUNT doesn't affect the comparison. Also not the double square brackets. This is now preferred over the single square brackets. It's less prone to errors when you forget quotes.

Upvotes: 0

anubhava
anubhava

Reputation: 786261

To count files on Unix systems properly use this script:

c=0
while read -d '' line; do
    ((c++))
done < <(find jvm -maxdepth 1 -type f -print0)

echo $c

This script will take care of filename with spaces or new lines as well.

Upvotes: 1

Related Questions