Search code examples
bashshelldirectorypathname

counting files, directories and subdirectories in a given path


I am trying to figure how to run a simple script "count.sh" that is called together with a path, e.g.:

count.sh /home/users/documents/myScripts

The script will need to iterate over the directories in this path and print how many files and folders (including hidden) in each level of this path.

For example:

  1. 7
  2. 8
  3. 9
  4. 10

(myScripts - 7, documents - 8, users -9, home - 10)

And by the way, can I run this script using count.sh pwd?


Solution

  • More or less something like that:

    #!/bin/sh
    
    P="$1"
    
    while [ "/" != "$P" ]; do
        echo "$P `find \"$P\" -maxdepth 1 -type f | wc -l`"
        P=`dirname "$P"`;
    done
    echo "$P `find \"$P\" -maxdepth 1 -type f | wc -l`"
    

    You can use it from the current directory with script.sh `pwd`