4

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
  • 3
    tree -d path/to/location or find /path/to/location -type d. Also, please don't post screenshots of text; just put the code into your question. Also also, don't parse ls. Just use for file in /path/to/location/*. – DopeGhoti Jun 18 '16 at 22:57
7

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.

  • any explanation why the original coded did not work. – Jasen Jun 19 '16 at 0:12
  • @Jasen that solution doesn't follow the sub-directories properly. -d check fails because current working directory is not set properly. So in the recursive calls a directory change is needed. – coffeMug Jun 19 '16 at 1:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.