John Bokma MexIT
freelance Perl programmer

mkdir: making several directories at once

Monday, December 1, 2008 | 0 comments

If you use the command line (shell) in Ubuntu a lot, like me, you probably are aware of the -p option of the mkdir command to create all directories in the given (relative) path that do not already exist.

For example, assuming that the Downloads directory doesn't exists, the following command:

mkdir -p /home/john/Downloads/web

Creates both the Downloads directory and its subdirectory web.

If the Downloads directory does exists - and even the web subdirectory - no error is given; the mkdir command just ignores each directory that already exists. Hence it's safe to use this command: no files will be deleted if the directory already exists.

But you can do much more using the -p option; you can create a complete directory tree with just a single command.

Creating a directory tree with mkdir

The power of the -p option is not limited to creating all non-existent directories in a path; you can create a complete directory tree with a single mkdir command.

First let start with a simple example: assume that besides the web subdirectory, which I use as the default download directory for Firefox, also a directory for active torrents and finished torrents is required. Or drawn as a tree using ASCII art:

        |                 |             |
  active-torrents  finished-torrents   web

This directory tree can be created using the following mkdir command:

mkdir -p Downloads/{active-torrents,finished-torrents,web}

Note how the directories at the same level are grouped between {} and separated by commas.

Note: don't be tempted to put a space after each comma, otherwise you end up with a {active-torrents, sub directory in Downloads, and with a finished-torrents, and web} directory at the same level as Downloads because a space is seen as an argument separator. Or: what follows the space is seen as the start of a entirely new path.

For a more complex example, the following directory tree:

     |         |        |
  branches    tags    trunk
               |        |        |
            cgi-bin   htdocs  scripts

can be created with the following command:

mkdir -p{branches,tags,trunk/{cgi-bin,htdocs,scripts}}

If you are using Subversion to keep files under version control you might recognize the directory tree structure.

Note how again {} is used to group a set of directories, and that an element in a set can consist of a directory followed by another set.

Also today

Please post a comment | read 0 comments | RSS feed