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.
Note: This is a snapshot of the wiki page from the BetterWays.dev wiki, you can find the latest, fully formatted version here: betterways.dev/creating-a-directory-tree-at-once-in-linux-unix.
Top comments (0)