Β· how to Β· 2 min read
How To: Create a directory tree with a single command (Linux, macOS)
Create tree folder structure with a single command
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
mkdirto 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
mkdircommands 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.