Traverse all subdirectories in and do something in Unix shell script

Use a for loop:

for d in $(find /path/to/dir -maxdepth 1 -type d)
do
  #Do something, the directory is accessible with $d:
  echo $d
done >output_file

It searches only the subdirectories of the directory /path/to/dir. Note that the simple example above will fail if the directory names contain whitespace or special characters. A safer approach is:

find /tmp -maxdepth 1 -type d -print0 |
  while IFS= read -rd '' dir; do echo "$dir"; done

Or in plain bash:

for d in /path/to/dir/*; do
  if [ -d "$d" ]; then
    echo "$d"
  fi
done

(note that contrary to find that one also considers symlinks to directories and excludes hidden ones)


I am a complete bash newbie, but a UN*X veteran. Although doubtless this can be done in Bash shell scripting, in the old days we used find [-maxdepth <levels>] <start-dir> -exec <command> ; to achieve this. You could do a man find and play around, perhaps until someone tells you how to do it in bash!


Looks like you want the filenames under each of the subdirs; the ls -l | awk is not robust enough, for what if those filenames comprise whitespace and/or newlines? The below find would work even for finds that donot happen to have the -maxdepth going for them:

find . ! -name . -type d -prune -exec sh -c '
   cd "$1" && \
   find "." ! -name . -prune  -type f
' {} {} \;