Creating a directory tree at once in Linux/Unix

📄 Wiki page | 🕑 Last updated: Oct 18, 2022

Instead of creating each directory in the tree separately, you can use brace expansion to do this in a single line:

mkdir -p testdir/{subdir1/subdir11/{subdir111,subdir112},subdir2,subdir3}

If we check the result with tree testdir, the result should be as expected:

testdir
├── subdir1
│   └── subdir11
│       ├── subdir111
│       └── subdir112
├── subdir2
└── subdir3

6 directories, 0 files

This works in most shells today, including bash and zsh.

How does it work?

Brace expansion is a similar mechanism to filename expansion, but the generated filenames don't need to exist. For example, if we put echo in front of the above command:

echo mkdir -p testdir/{subdir1/subdir11/{subdir111,subdir112},subdir2,subdir3}

We'll see the expanded command:

mkdir -p testdir/subdir1/subdir11/subdir111 testdir/subdir1/subdir11/subdir112 testdir/subdir2 testdir/subdir3

Note: we have to use the mkdir's -p option to make the parent directories automatically, otherwise the command would fail.


Ask me anything / Suggestions

If you have any suggestions or questions (related to this or any other topic), feel free to contact me. ℹī¸


If you find this site useful in any way, please consider supporting it.