Skip to content

Listing Directories in Linux and Limiting Depth⚓︎

Why ls doesn’t work⚓︎

ls doesn’t natively support recursion depth limiting.

While you can use shell wildcards as in ls */*/, you must know how many depths exist. If you use two wildcards, and only have one subdirectory, you will receive an error.

Bash
1
2
$ ls */*/
/usr/bin/ls: cannot access */*/: No such file or directory

There are better ways than using shell wildcards in this instance.

Alternatives⚓︎

tree⚓︎

tree allows for limiting depth, and many other options. Human readable units, permissions, size, etc. This is an additional package and may not be installed, but it allows for the greatest flexibility.

Bash
1
2
3
tree -d -L 2 /NAS
tree -L 2 -p -h /NAS
ansible -m raw -a 'tree -d -L 2 /NAS' inv_grp
Text Only
1
2
3
4
5
6
7
8
$ tree -d -L 2 /NAS
/NAS
├── archive
│   └── software
└── installers
    ├── app1
    ├── app2
    └── app3

find⚓︎

find can limit to a maxdepth, however, it will be the output of ls -dils and may be more text than you need.

Bash
1
find . -maxdepth 2 -type d -ls
Text Only
1
2
3
4
$ find . -maxdepth 2 -type d -ls
 33567703      0 drwx------   5  user     staff         158 Jan 31 12:54 .
 67552627      0 drwx------   2  user     staff          29 Aug 23 13:54 ./.ssh
 33925592      0 drwx------   3  user     staff          20 Aug 23 13:59 ./.config

Source⚓︎