Linux mkdir Command


The mkdir command in Ubuntu (and other Linux-based systems) is used to create new directories. This command allows you to make one or more directories and set permissions as needed.

Syntax

mkdir [options] directory_name
  • [options]: Flags to customize the behavior of mkdir.
  • directory_name: The name of the directory to create. You can specify multiple directory names, separated by spaces, to create multiple directories at once.

1. Basic Usage of mkdir

To create a single directory in the current directory, simply type:

mkdir new_directory

Example:

mkdir my_project

This creates a new directory named my_project in the current directory.

2. Creating Multiple Directories

You can create multiple directories at once by listing them separated by spaces:

mkdir dir1 dir2 dir3

This creates dir1, dir2, and dir3 in the current directory.

3. Creating Parent Directories with -p

The -p option (parent) allows you to create a nested directory structure, creating parent directories as needed.

mkdir -p parent/child/grandchild

In this example:

  • If parent doesn’t exist, it will be created.
  • The command then creates child inside parent and grandchild inside child.

Without -p, the command will fail if any part of the path doesn’t exist.

4. Setting Permissions with -m

The -m option lets you specify permissions for the new directory. Permissions are set using octal notation (e.g., 755).

mkdir -m 755 new_directory

In this example:

  • 755 sets permissions so the owner has full read, write, and execute access, while group and others have read and execute access.

5. Checking Success and Errors

After using mkdir, use ls to verify the directory was created. If you don’t have the necessary permissions to create a directory (e.g., in a restricted location), mkdir will display an error.

Example error:

mkdir /restricted_directory

Output:

mkdir: cannot create directory ‘/restricted_directory’: Permission denied

In such cases, use sudo if you need elevated permissions:

sudo mkdir /restricted_directory

Examples

Basic Creation

mkdir my_folder

Multiple Directories

mkdir project1 project2 project3

Nested Directories

mkdir -p projects/code/scripts

Setting Permissions

mkdir -m 700 private_folder

Summary

The mkdir command is essential for creating directories in Ubuntu, with options to create nested directories (-p), set permissions (-m), and handle multiple directories in one command. It’s a straightforward but powerful command for organizing and managing directories.