Monday, July 5, 2010

Good Habit #1: Make directory trees in a single swipe

Listing 1 illustrates one of the most common bad UNIX habits around: defining directory trees one at a time.

Listing 1. Example of bad habit #1: Defining directory trees individually

~ $ mkdir tmp
~ $ cd tmp
~/tmp $ mkdir a
~/tmp $ cd a
~/tmp/a $ mkdir b
~/tmp/a $ cd b
~/tmp/a/b/ $ mkdir c
~/tmp/a/b/ $ cd c
~/tmp/a/b/c $

It is so much quicker to use the -p option to mkdir and make all parent directories along with their children in a single command. But even administrators who know about this option are still caught stepping through the subdirectories as they make them on the command line. It is worth your time to conscientiously pick up the good habit:

Listing 2. Example of good habit #1: Defining directory trees with one command

~ $ mkdir -p tmp/a/b/c
 
You can use this option to make entire complex directory trees, which are great to use inside scripts; not just simple hierarchies. For example:

Listing 3. Another example of good habit #1: Defining complex directory trees with one command

~ $ mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

In the past, the only excuse to define directories individually was that your mkdir implementation did not support this option, but this is no longer true on most systems. IBM AIX® mkdir, GNU mkdir, and others that conform to the Single UNIX Specification now have this option.

No comments:

Post a Comment