Creating a directory tree at once in Linux/Unix
📄 BetterWays.dev wiki page | 🕑 Last updated: Oct 18, 2022Instead 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.
Comments and suggestions
If you find this site useful, please consider supporting it. Supporters also get access to some extras.