Is there a way for the user to specify how many folder levels my script will search?

Viewed 29

im building a small bash script project.My code getting 2 arguments, one path to search and one number that tells me how many folders level i have to analyze. For Example if the user gives the number 2 my programm it must search all directories within it and all directories within them.

#!/bin/bash

function check_dir {
    echo Checking dir : $1
    for f in `ls $1`
    do
        if [ -d $1/$f ]
        then
            dirs_num=$(($dirs_num+1))
            check_dir $1/$f
        else    
            files_num=$(($files_num+1))
            size=`stat -c%s $1/$f`
            echo $1/$f - $size
        fi
    done
}

files_num=0
dirs_num=0
depth=$2
check_dir $1
echo "Found $files_num files and $dirs_num dirs."

This is my code so far, im giving the path when i execute it but it gives me result for any folder that it finds.So how can i stop this loop? Thank you.

1 Answers

Use .

Quoteth the manpage

 -maxdepth levels
       Descend at most levels (a non-negative integer) levels of directories
       below  the command line  argu‐ments.  -maxdepth 0  means only apply the
       tests and actions to the command line arguments.

With a bit of , GNU , and , you can do what you want in a *safe manner.

#!/bin/bash

awk '
  BEGIN{ RS="\0" } # Non-portable, requires GNU awk
  $1 != dir{
        print "Checking dir : " $1
        dcnt++
        dir = $1
  }
  {
        print $1$2 " - " $3
        fcnt++
  }
  END{
        print "Found " fcnt " files and " dcnt " dirs."
  }' <(find "$1" -maxdepth "$2" -type f -printf "%h\t%f\t%s\0" | LC_ALL=C sort -z )

By *safe I mean each record is NUL terminated and doesn't parse ls

Related