Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively list subdirectories in Bash without using "find" or "ls" commands?

Tags:

bash

I know you can use the find command for this simple job, but I got an assignment not to use find or ls and do the job. How can I do that?

like image 463
Raghubansh Mani Avatar asked Jan 28 '10 11:01

Raghubansh Mani


People also ask

How can I list subdirectories recursively?

Linux recursive directory listing using ls -R command. The -R option passed to the ls command to list subdirectories recursively.

How do I list all files in subdirectories?

By default, ls lists just one directory. If you name one or more directories on the command line, ls will list each one. The -R (uppercase R) option lists all subdirectories, recursively.


2 Answers

you can do it with just the shell

#!/bin/bash
recurse() {
 for i in "$1"/*;do
    if [ -d "$i" ];then
        echo "dir: $i"
        recurse "$i"
    elif [ -f "$i" ]; then
        echo "file: $i"
    fi
 done
}

recurse /path

OR if you have bash 4.0

#!/bin/bash
shopt -s globstar
for file in /path/**
do
    echo $file
done
like image 90
ghostdog74 Avatar answered Oct 10 '22 02:10

ghostdog74


Try using

tree -d
like image 21
Alberto Zaccagni Avatar answered Oct 10 '22 03:10

Alberto Zaccagni