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
1
  • 4
    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/*. Commented Jun 18, 2016 at 22:57

1 Answer 1

8

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.

2
  • any explanation why the original coded did not work. Commented Jun 19, 2016 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. Commented Jun 19, 2016 at 1:58

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.