Linux commands: mkdir

By

Learn how the Linux mkdir command creates folders, makes several at once in a single call, and builds nested directories in one go with the -p option.

~~~

You create folders using the mkdir command:

mkdir fruits

Verify it worked with ls, which now lists the new folder.

If a folder with that name already exists, mkdir refuses and tells you:

mkdir fruits
# mkdir: fruits: File exists

Nothing gets overwritten. The existing folder and everything inside it are safe.

You can create multiple folders with one command:

mkdir dogs cars

You can also create multiple nested folders by adding the -p option:

mkdir -p fruits/apples

The -p matters here. Without it, mkdir fruits/apples fails with No such file or directory when fruits doesn’t exist yet, because plain mkdir only creates the final piece of the path. -p creates every missing parent along the way.

-p has a second useful behavior: it stays silent when the directory already exists, instead of failing. That makes the command safe to run twice, which is why mkdir -p shows up in so many scripts — the script works on the first run and on every run after.

Add -v and the command narrates each directory it creates, a nice confirmation when -p builds several levels at once:

mkdir -pv fruits/pears

Options in UNIX commands commonly take this form. You add them right after the command name, and they change how the command behaves. You can often combine multiple options, too — -pv above is -p and -v together.

You can find which options a command supports by typing man <commandname>. Try now with man mkdir for example (press the q key to esc the man page). Man pages are the amazing built-in help for UNIX.

Tagged: CLI · All topics
~~~

Related posts about cli: