(One)-minute geek news

Group talks, Laboratoire de Chimie, ENS de Lyon

Recursive directory creation


Most linux utilities for files manipulation are equipped with a recursive option, this is also true for the mkdir command.

Common recursive-equipped commands

Many files manipulation commands support a recursive option, usually activated with -r (or -R if -r already has an other signification. So that, in fact, the "natural" recursive option is usually -R for most POSIX/GNU utilities:

  • cp -r or cp -R copies a directory and all its subdirectories recursively. Note that a cp -r does not preserve links, use the archiving -a option instead. Note: the mv command is recursive by default.
  • rm -r or rm -R remove a directory and all its subdirectories recursively.
  • grep -r or grep -R searches files recursively for lines matching a given pattern (this could also be done with a simple globstar).
  • ls -R lists subdirectories recursively (while -r reverse the sorting order).
  • chmod, chown, ... POSIX commands also have a -R recursive option.

Recursive mkdir

What about the mkdir command? I personally face constantly a "mkdir: cannot create directory 'new_dir/new_dir2': No such file or directory" error whenever I want to create a directory and a subdirectory at the same time. For example, the command mkdir /tmp/rand.8f3d9/rand.2o4s8 will most certainly fail, forcing you to execute beforehand mkdir /tmp/rand.8f3d9. Painful isn't it?

Fortunately, computer scientists are lazy, and usually come up with solutions against extra typing.

Indeed, similarly to the recursive (descending) option, mkdir features a parents (ascending) option -p, that enable the (recursive) creation of parent directories, if needed.

Therefore, our previous example simply becomes mkdir -p /tmp/rand.8f3d9/rand.2o4s8

Even better, simply add the alias alias mkdir="mkdir -p" into your ~/.bashrc file, and enjoy hassle-free directories creation!