My new 564-page book, Shell Scripting, published by Wiley, is on sale now. Please click "Like" on the left if you are on Facebook, or just click here to get the book.

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
My new 564-page book, Shell Scripting, published by Wiley, is on sale now. Please click "Like" on the left if you are on Facebook, or just click here to get the book.
Steve's Bourne / Bash shell scripting tutorial
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon

Want to take the tutorial with you?

My Shell Scripting Book:
    Shell Scripting, Expert Recipes for Linux, Bash and more
is available online and from all good booksellers.

Buy my 600-page Shell Scripting Book...

From Amazon USA:

From Amazon UK:

For Kindle:

Or From other retailers

You can also find the book, and join a shell scripting community, on Facebook:


Option Two: Buy the 70-page PDF (£4.99/$9.99/€6.99)
(Free Sample)

And you can always Download my Free Shell Scripting Cheatsheet PDF