Ashley Sheridan​.co.uk

Using brace expansion to create nested directory structures

Posted on

Tags:

When setting up a new project it's often required to set up the same old directory structures. You could do this manually, but where's the fun in that? You can do this much more quickly in the terminal with brace expansion.

Consider the following directory structure:

  • project_dir
    • www
      • img
      • js
      • css
    • logs

This entire directory structure can be created in one small BASH command:

mkdir -p project_dir/{logs,www/{img,js,css}}

In BASH, the braces indicate a list of items that the shell should expand. The -p flag used in the mkdir call just ensures that no warnings are thrown about directories already existing when it attempts to create them. Without this it would not be able to create all the ones required without stopping on the first error.

This can easily be saved as a user script in ~/bin and tweaked to allow an argument to be passed as the project name, making this more flexible and negating the need to type it out each time.