Shell – Print recursively all directories and subdirectories

directoryrecursiveshell-script

I am trying to print all directories and sub directories with a recursive function but I get only the first directory. Any help?

counter(){
    list=`ls $1`
    if [ -z "$(ls $1)" ]
    then 
        exit 0
    fi
    echo $list
    for file in $list
    do 
      if [ -d $file ]
      then 
            echo $file
            counter ./$file
      fi
    done
}

counter $1

Best Answer

You can use something similar to this:

#!/bin/bash

counter(){
    for file in "$1"/* 
    do 
    if [ -d "$file" ]
    then 
            echo "$file"
            counter "$file"
    fi
    done
}

counter "$1"

Run it as ./script.sh . to recursively print directories in under the current directory or give the path to some other directory to traverse.

Related Question