Skip to content

The mkdir Command: Creating Directories in Linux

Summary

The mkdir command is a fundamental Linux utility used to create directories (folders). This post will guide you through its basic usage, common use cases, and helpful flags.

Introduction

The mkdir command, short for "make directory," is essential for organizing files and data within a Linux system. It allows you to create new directories, enabling a structured file system. Without it, you'd be stuck with a single, unorganized folder for all your files!

Use Case and Examples

Creating a single directory

mkdir my_new_directory
This command creates a new directory named "my_new_directory" in your current working directory.

Creating multiple directories

mkdir dir1 dir2 dir3
This command creates three directories: "dir1", "dir2", and "dir3" in the current working directory.

Creating a directory with a specific path

mkdir /home/user/documents/new_project
This command creates a directory named "new_project" within the specified path: "/home/user/documents". This requires you to have the necessary permissions to create the directory in the /home/user/documents location.

Creating parent directories if they don't exist

mkdir -p /home/user/documents/another_project/sub_directory
The -p flag (or --parents) is crucial here. If the directories "/home/user/documents" or "/home/user/documents/another_project" don't exist, mkdir -p will create them along with "sub_directory". Without -p, the command would fail if the parent directories are missing.

Commonly used flags

Flag Description Example
-p, --parents Create parent directories as needed; no error if existing. mkdir -p /path/to/new/directory (Creates path, to, and new if they don't exist.)
-m, --mode=MODE Set file mode (as in chmod), not a=rwx - umask. mkdir -m 755 my_directory (Creates my_directory with read, write, and execute permissions for the owner, and read and execute for the group and others.)
-v, --verbose Print a message for each created directory. mkdir -v new_dir (Prints "mkdir: created directory 'new_dir'")
-Z, --context[=CTX] Set the SELinux security context to CTX, or to the default type if CTX is unspecified. mkdir -Z system_u:object_r:tmp_t:s0 secure_directory (Creates secure_directory with the specified SELinux context. SELinux must be enabled and configured for this to be effective. Consult your SELinux documentation.)


Share on Share on

Comments