Join my Bash scripting course on Udemy πŸ‘€

Make multiple subdirectories at once with mkdir

October 20, 2020  ‐ 2Β min read

The linux shell command to make a new directory. If works pretty pretty straightforward: you want to make a directory, you give the name as an argument, and you get a directory. If you want to make some subdirectories as well however mkdir isn't as friendly.

Lets say you want to make a directory called sub, which should have a directory in it called way, which in its turn should have a subdirectory called sandwich.

If you try it like this, mkdir starts to complain. It expects both the sub and way directories to exists and plans on just making the sandwich directory.

$ mkdir sub/way/sandwich
mkdir: cannot create directory β€˜sub/way/sandwich’: No such file or directory

The boring option is to make this command into a three-parter. Make the first, second and third directory separately.

$ mkdir sub
$ mkdir sub/way
$ mkdir sub/way/sandwich

A faster way is to use the -p option with the first command. The -p option makes sure that parent directories are created as well if necessary.

$ mkdir -p sub/way/sandwich

And there you go.

$ tree sub
sub
└── way
    └── sandwich

2 directories, 0 files

Create multiple subdirectories with mkdir

By using braces({}) you can create multiple subdirectories at once. This is actually called "Brace Expansion" and useful in other commands as well.

$ mkdir -p  sub/{way,system}/sandwich
$ tree sub
sub
β”œβ”€β”€ system
β”‚Β Β  └── sandwich
└── way
    └── sandwich

4 directories, 0 files

Learning more

The best way to learn more is to use Bash. A lot. Don't forget that Google is your friend.

In case you learn well from books I would recommend these.