20

I'm learning bash scripting and have written a script to count the files and directories in the directory that is supplied as argument. I have it working one way which seems odd to me and am wondering if there is a simpler way of doing it.

I have commented out the code that will work, but left it in as a comparison. I am trying to get the for-loop working, instead using if statements inside it to detect if an item in the given location is a file or a directory.

Edit: I just found out that the commented code counts all files and directories in the subdirectories of the given location as well! Is there any way to prevent this and just count the files and directories of the given location?

#!/bin/bash

LOCATION=$1
FILECOUNT=0
DIRCOUNT=0

if [ "$#" -lt "1" ]
then
    echo "Usage: ./test2.sh <directory>"
    exit 0
fi

#DIRS=$(find $LOCATION -type d)
#FILES=$(find $LOCATION -type f)

#for d in $DIRS
#do
#   DIRCOUNT=$[$DIRCOUNT+1]
#done

#for f in $FILES
#do
#   FILECOUNT=$[$FILECOUNT+1]
#done

for item in $LOCATION
do
if [ -f "$item" ]
    then
         FILECOUNT=$[$FILECOUNT+1]
    elif [ -d "$item" ]
        then
         DIRCOUNT=$[$DIRCOUNT+1]
fi
done

echo "File count: " $FILECOUNT
echo "Directory count: " $DIRCOUNT

For some reason the output of the for-loop, no matter where I point the location to, always returns:

File count: 0 , Directory count: 1
7
  • Your whole script is broken if there happens to be spaces in file names. As you're learming, my first advice is: Use More Quotes! Commented Dec 5, 2012 at 15:57
  • Another comment: I can tell that your sources for learning bash are outdated and don't show good practices. Commented Dec 5, 2012 at 15:58
  • On Filename Expansion consider reading: bash.cyberciti.biz/bash-reference-manual/… Commented Dec 5, 2012 at 16:00
  • Hi, I don't understand this, where are there spaces in file names? Commented Dec 5, 2012 at 16:08
  • You could have a space in a filename. Try this: touch "hello Kitty", you'll have a file with a space in its name. Worse, try touch $'hello\nKitty', you'll have a file the name of which will not be easy to handle with the methods involving find. Commented Dec 5, 2012 at 16:20

5 Answers 5

20

Use find as shown below. This solution will count filenames with spaces, newlines and dotfiles correctly.

FILECOUNT="$(find . -type f -maxdepth 1 -printf x | wc -c)"
DIRCOUNT="$(find . -type d -maxdepth 1 -printf x | wc -c)"

Note that the DIRCOUNT includes the current directory (.). If you do not want this, subtract 1.

((DIRCOUNT--)) # to exclude the current directory
Sign up to request clarification or add additional context in comments.

2 Comments

This is obviously the best possible method in this particular case! As dogbane mentioned, it handles all possible cases of files having funny symbols in their name, and also works well with directories that contain a lot of files (which is not the case for the bash solutions using globbing). One thing, though, my find complains about -maxdepth 1 being given after the -type f option. (Another thing, the double quotes are not necessary here, but it never hurts to use them).
Note that the -printf primary is not available on macOS.
15

To just solve the problem you can use:

FILECOUNT=$(find $LOCATION -type f | wc -l)
DIRCOUNT=$(find $LOCATION -type d | wc -l)

find will look for all files (-type f) or directories (-type d) recursively under $LOCATION; wc -l will count the number of lines written to stdout in each case.

However if you want to learn, the bash script may be a better way. Some comments:

  • If you want to look for files/directories in $LOCATION only (not recursively under their subdirectories etc), you can use for item in $LOCATION/*, where the * will expand to the list of files/directories in the $LOCATION directory. The missing * is why your original script returns 0/1 (becasue the $LOCATION directory itself is the only item counted).
  • You may want to check first that $LOCATION is actually a directory with [ -d $LOCATION ].
  • For arithmetic expressions, use $(( ... )), for example FILECOUNT=$(( FILECOUNT + 1 )).
  • If you want to find all files/directories recursively, you could combine find with a loop.

Example:

find $LOCATION | while read item; do
    # use $item here...
done

2 Comments

Yes, the $LOCATION/* code worked perfectly. Why $(( ... )) instead of $[] ? Performance related?
@AlanSmith, $[...] is deprecated syntax, I can't even find it in man bash. The modern version is $(( ... )) (though they seem to work the same way). For your task you could just use ((++FILECOUNT)) too. See stackoverflow.com/questions/2188199/….
5

You're not iterating over the list of files inside the given directory; add /* after $LOCATION. Your script should look like:

...
for item in $LOCATION/*
do
...

As pointed by dogbane, just adding /* will count only files that does not begin with .; for doing so, you shall do the following:

...
for item in $LOCATION/* $LOCATION/.*
do
...

4 Comments

Thats the actual main issue in the script.
That's the answer I am looking for! Thanks. The other solutions here all counted the files and directories of the sub directories of the location as well, which I didn't want. Cheers.
this will not count dot files i.e. filenames starting with a ..
@dogbane I've added this case in the example; thanks for pointing it out. Regards!
4

... am wondering if there is a simpler way of doing it.

If you say so ;)

Alternatively, reduce your script to

find /path/to/directory | wc -l

For current directory, do:

find . | wc -l

3 Comments

Note: It counts . as a file too. So with only two regular files which I guess you want to count, this will print 3.
He's looking for a way to distinguish the counts of dirs and files - that's why he has 2 counters in his code. Your find gives the total count, not distinguishing between file types.
if i am using the command " find . | wc -l " it is giving 1 extra count. Like if the file count in the directory is 4 , for me this command is giving 5 in the place of 4.
2

Use

find $LOCATION -maxdepth 1 -type f | wc -l

For the count of files, and

find $LOCATION -maxdepth 1 -type d | wc -l

For counting directories

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.