Sometimes you need to create a tree directory structure or create many directories with a single command. I recently faced such a task while developing the custom software deployment script. Let’s imagine that you need to make the following folders:
└── app
├── bin
│ └── internal
├── config
│ ├── custom
│ └── templates
└── tmp
This can be achieved with a straight forward solution:
mkdir app
mkdir app/bin
mkdir app/bin/internal
mkdir app/config
mkdir app/config/custom
mkdir app/config/templates
mkdir app/tmp
However, the solution above isn’t beautiful, and it doesn’t use all power of mkdir
. Can you imagine that code above is replaceable with the following single line of code:
mkdir -p app/{bin/internal,config/{custom,templates},tmp}
- -p parameter forces
mkdir
to create sub-directories of a directory. It will create the parent directory first if it does not exist. And if it exists, then no error will be printed and will move further to create sub-directories. - {custom,templates} - the words in the curly braces represent “brace expansion list”. Each of the items in the brace expansion list is appended separately to the preceding path. It is similar to looping through those items and executing those
mkdir
commands separately. Also, as you can see from the example above, “brace expansion lists” can be nested, which allows creating any complicated tree structures in a single line.
That is it. I hope your shell scripts will become shorter and more effective from now on.