mkdir: Creating multiple subdirectories in one command

Apr 15 2010

Often times, I want to create a full directory structure, and I'd like to do it with just one call to mkdir. That is, I want to create a root directory and multiple subdirectories all at once. Here's how to do this.

mkdir -p myProject/{src,doc,tools,db}

The above creates the top-level directory myProject, along with all of the subdirectories (myProject/src, myProject/doc, etc.). How does it work? There are two things of note about the command above:

  • The -p flag: This tells mkdir to create any leading directories that do not already exist. Effectively, it makes sure that myProject gets created before creating myProject/src.
  • The {} lists: The technical name for these is "brace expansion lists". Basically, the shell interprets this as a list of items that should be appended individually to the preceding path. Thus, a/{b,c} is expanded into a/b a/c.

You can nest brace expansion lists. That means you can create more complex sets of subdirectories like this:

mkdir -p myProject/{src,doc/{api,system},tools,db}

Notice that this creates two directories inside of doc/. <!--break-->