Creating a directory tree at once in Linux/Unix
đ 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.
Ask me anything / Suggestions
If you find this site useful in any way, please consider supporting it.