A handy Unix shell tip

Apr 5, 2013 00:00 · 249 words · 2 minute read

As a configuration management and release engineer, the vast entirety of my work is on *nix - Red Hat primarily and the odd Solaris installation.

While working on the command line with that black window and white text is bliss, I’m growing ever more conscious of the way I work - working smart.

Here’s a tip that I picked up recently and it has definitely improved my speed at one particularly mundane task - creating folder structures.

Assume the following folder structure that needs to be created:


The regular scenario would have you going:

shell$ mkdir folderA
shell$ cd folderA
folderA$ mkdir folderB
folderA$ cd folderB
folderB$ mkdir folderB1
folderB$ cd ..
folderA$ mkdir folderC
folderA$ cd folderC
folderC$ mkdir folderC1

Grossly inefficient.

With UNIX, there’s always a better way at this -

use the -p (--parents) parameter with the mkdir command and you’re done in a split second.

Like so:

mkdir -p folderA/{folderB/folderB1,folderC/folderC1}

The -p parameter creates parent folder structures as it sees them and ignores if they already exist.

The curly braces expand the list of comma separated values as individual parameters for the mkdir command. A point to note here is tt include a space between the comma and the next word.

Pretty useful tip to create destination folder tree structures via a shell script. mkdir should be universally supported on all distributions that conform to the UNIX specification - that means most of them in today’s time.