Working with files

Linux commands: mkdir

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

The command prints nothing when it works. That’s normal for UNIX commands: silence means success. Run ls and you’ll see the new folder in the list.

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 only creates the last piece of the path, and fails if the parents are missing:

mkdir fruits/apples/red
mkdir: fruits/apples: No such file or directory

fruits exists, but apples doesn’t, so mkdir has nowhere to put red. Add -p and it creates every missing folder along the way, in one go.

-p has a second useful behavior: it stays silent when the folder 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 folder it creates. It’s a nice confirmation when -p builds several levels at once:

mkdir -pv fruits/pears
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.

I use mkdir -p almost by default. When I set up a project I type something like mkdir -p src/components src/pages public/images and the whole structure appears at once, no matter which folders already exist.

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

Lesson completed