Bash – Traverse all subdirectories in and do something in Unix shell script

bashshell-script

I want my shell script to visit all subdirectories in a main directory. Do something in directories, sent output to a spool file and move on to next directory.
Consider
Main Dir = /tmp
Sub Dir = A B C D (Four sub directories)

Best Answer

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)

Related Question