Directory Traversal

This is an example of two methods for doing a depth-first traversal of a directory tree.

traverse.sh uses subshells to traverse each subdirectory.
traverse2.sh uses a single shell, which is probably more efficient.
tree.tar.gz (download) contains a simple directory tree for testing with:


a/
a/ac/
a/A
a/ad/
a/ad/Another File
a/aa/
a/aa/AA
a/File With Spaces
a/ab/
a/ab/AB
d/
d/D
d/da/
d/db/
d/db/This is a file
d/dc/
d/dd/
README
c/
c/cb/
c/C
c/ca/
c/cc/
c/cd/
b/
b/ba/
b/bb/
b/B
b/bc/
b/bd/
traverse2.sh

The script traverse.sh (download) runs like this:

Directory: a
  File: A
  Directory: aa
    File: AA
  Directory: ab
    File: AB
  Directory: ac
  Directory: ad
    File: Another File
  File: File With Spaces
Directory: b
  File: B
  Directory: ba
  Directory: bb
  Directory: bc
  Directory: bd
Directory: c
  File: C
  Directory: ca
  Directory: cb
  Directory: cc
  Directory: cd
Directory: d
  File: D
  Directory: da
  Directory: db
    File: This is a file
  Directory: dc
  Directory: dd
File: README
File: traverse2.sh
File: traverse.sh
File: tree.tar.gz

The script traverse2.sh (download) runs like this:

Directory: ./a
  File: ./a/A
  Directory: ./a/aa
    File: ./a/aa/AA
  Directory: ./a/ab
    File: ./a/ab/AB
  Directory: ./a/ac
  Directory: ./a/ad
    File: ./a/ad/Another File
  File: ./a/File With Spaces
Directory: ./b
  File: ./b/B
  Directory: ./b/ba
  Directory: ./b/bb
  Directory: ./b/bc
  Directory: ./b/bd
Directory: ./c
  File: ./c/C
  Directory: ./c/ca
  Directory: ./c/cb
  Directory: ./c/cc
  Directory: ./c/cd
Directory: ./d
  File: ./d/D
  Directory: ./d/da
  Directory: ./d/db
    File: ./d/db/This is a file
  Directory: ./d/dc
  Directory: ./d/dd
File: ./README
File: ./traverse2.sh
File: ./traverse.sh
File: ./tree.tar.gz
Steve's Bourne / Bash shell scripting tutorial
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon