Published at
Updated at
Reading time
1min

I came across this shell one-liner command to create a bunch of new directories recursively today! ๐Ÿ’ช

mkdir -p new-dir/{foo,baz}/whatever-{1,2}/{a,b};

# new-dir
# โ”œโ”€โ”€ baz
# โ”‚  โ”œโ”€โ”€ whatever-1
# โ”‚  โ”‚  โ”œโ”€โ”€ a
# โ”‚  โ”‚  โ””โ”€โ”€ b
# โ”‚  โ””โ”€โ”€ whatever-2
# โ”‚     โ”œโ”€โ”€ a
# โ”‚     โ””โ”€โ”€ b
# โ””โ”€โ”€ foo
#    โ”œโ”€โ”€ whatever-1
#    โ”‚  โ”œโ”€โ”€ a
#    โ”‚  โ””โ”€โ”€ b
#    โ””โ”€โ”€ whatever-2
#       โ”œโ”€โ”€ a
#       โ””โ”€โ”€ b

The one-liner's magic is based on two things: mkdir's -p flag and a shell feature called brace expansion.

-p instructs mkdir to create intermediate directories as required. It's recursive directory creation so to say.

And brace expansion allows magic like the following.

$ echo {a..z} 
a b c d e f g h i j k l m n o p q r s t u v w x y z

Magic!

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles