Wednesday, December 03, 2008

Bash Script to get maximum directory depth


They used echo sounding to figure out what the deepest part of the ocean was. Too bad the echo command in Linux does something totally different..

I needed a way to figure out the deepest part of a directory structure, using standard Linux commands only (no php/perl/python etc.).

e.g. if the directory structure is as follows -

d1
->d2
->->d3
->->->d4
->d5
->->d6


I wanted a shell script which will give me the answer "4" (i.e. depth of the deepest directory - d4).
A quick query posted on the local linux user group got me the solution


 find . -printf '%d\n' | sort -n  | tail -1


Works like a charm!

For those times when the -printf switch is not available for the find command (for example if you are running busybox instead of bash), here is a handy alternative -

find -type d | awk -F'/' '{print NF-1 "\n"}' | sort -n | tail -1


But this will not work for absolute directory names as then the depth of the base path will also be considered.

So here is the working solution for busybox users -

basedir="/home/something/"
find "$basedir" | sed "s#$basedir##g" | awk -F'/' '{print NF}' | sort -n | tail -1


However, if one is using gawk, or a modern awk, one can get it to replace sed (and, with some more work, probably sort, and tail also), viz.

basedir="/home/something/"
find "$1" | gawk -vbasedir="$1" -F/ '{gsub(basedir, "", $0); print NF-1}' | sort -n | tail -1


Great!

1 comment:

Philippe said...

Many thx, crystal clear, and really good to show the whole scope, incl busy box :-)

I saved some times thx to your explanation.