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:

├── 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.

Comments and suggestions

You can use this form to submit a suggestion or a comment.

If you find this site useful, please consider supporting it. Supporters also get access to some extras.