Website Vidya
Linux & ServersStep-by-Step Guide

mkdir Command in Linux: Create Directories & Parent Trees

Learn mkdir command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
12 min read
PDF Cheat Sheet
mkdir Command in Linux: Create Directories & Parent Trees
AI Executive SummaryWebsiteVidya AI

12 min read

Learn mkdir command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What mkdir Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Organizing application hierarchies, log paths, mount points, and configuration trees begins with the mkdir command in linux. Bundled as part of GNU coreutils on virtually every Linux distribution, mkdir provides a direct command-line interface to the kernel's directory-creation system call while supporting recursive path construction, atomic initial permission assignment, and SELinux security context labeling.

While creating a single directory in your home folder is straightforward, production shell scripting requires deeper mastery of how mkdir interacts with process umask values, how -p guarantees idempotency in repeatable deployment scripts, and how atomic permission setting with -m prevents security race conditions when provisioning sensitive credential directories.

This comprehensive guide explores the kernel inode mechanics behind mkdir, details all POSIX and GNU flags, demonstrates six practical terminal examples including nested brace expansion, and shares production-ready patterns for lock-free concurrency and secure directory scaffolding.

Advertisement
mkdir Command in Linux: Create Directories & Parent Trees — syntax, flags, and practical terminal workflow diagram
mkdir Command in Linux: Create Directories & Parent Trees — command syntax, key options, and production workflow reference.

What mkdir Does and When to Use It

When mkdir executes, it invokes the Linux kernel mkdir(2) or mkdirat(2) system call. Inside the Virtual File System (VFS) and the underlying filesystem driver (such as ext4, XFS, or Btrfs), creating a directory allocates a new inode marked with the S_IFDIR file type mode, initializes two mandatory directory entries—the self-reference dot (.) pointing to the new inode and the parent reference dot-dot (..) pointing to the parent directory's inode—and increments the parent directory's hard link count (st_nlink) by one.

By default, mkdir passes a base mode of 0777 (octal rwxrwxrwx) to the mkdir(2) syscall, which the Linux kernel immediately bitwise-ANDs with the bitwise complement of the calling process's umask (mode & ~umask). On standard systems with a umask of 0022, new directories receive 0755 (drwxr-xr-x) permissions; on systems using user private groups with a umask of 0002, they receive 0775 (drwxrwxr-x). Crucially, the mkdir(2) system call is strictly atomic at the VFS layer: if two processes attempt to create the exact same directory path simultaneously without -p, the kernel guarantees that exactly one succeeds (exit 0) and the other fails with EEXIST.

At the operating system level, mkdir (distributed in coreutils) interfaces with the Linux kernel through standard C library system calls and virtual filesystems. Understanding how mkdir resolves file descriptors, kernel structures, and exit status codes helps system administrators predict performance on high-load production servers.

Availability and Installation Across Linux Distributions

The mkdir utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether mkdir is installed and inspect which binary path and version your shell resolves:

type -a mkdir
mkdir --version 2>/dev/null || man -f mkdir

# Illustrative output (reviewed against documentation)
mkdir is /usr/bin/mkdir
mkdir (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

mkdir [OPTION]... DIRECTORY...

The mkdir command accepts optional flags followed by one or more whitespace-separated DIRECTORY operands: mkdir [OPTION]... DIRECTORY.... Each operand can be a relative path (resolved against the shell's current working directory, $PWD) or an absolute path starting from the root filesystem (/). When multiple directory names are supplied in a single invocation, mkdir processes each operand sequentially from left to right.

If any target path contains spaces or special shell metacharacters, you must enclose the path in quotes (e.g., mkdir "Q4 Financial Reports") or escape the spaces with backslashes; otherwise, the shell splits the string on whitespace and instructs mkdir to create separate directories for each word.

  • 0 — All specified directories were created (or already existed when -p was supplied) without error.
  • 1 — One or more directories could not be created due to EEXIST (file exists without -p), ENOENT (missing parent without -p), EACCES (permission denied), or ENOSPC (no space/inodes left).
  • 2 — Invalid command-line option or malformed mode string passed to -m.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-p--parentsCreates missing intermediate parent directories as needed and suppresses EEXIST errors if the target directory already exists.
-m--mode=MODESets the file permission bits of the terminal created directory to MODE (symbolic or octal like 0700), bypassing the process umask.
-v--verbosePrints a confirmation message to standard output for every directory and intermediate parent directory created.
-Z(SELinux)Sets the SELinux security context of each created directory to the default type defined by system policy for that path.
--context--context[=CTX]Like -Z, or if CTX is specified, sets the SELinux or SMACK security context of created directories to CTX.
--help--helpDisplays the GNU coreutils command-line usage summary and exits with status 0.
--version--versionOutputs the installed GNU coreutils version and licensing metadata.

A common subtlety involves combining -p (--parents) and -m (--mode). When you execute mkdir -p -m 0700 /opt/app/data/secrets where neither /opt/app nor /opt/app/data exists yet, the explicit -m 0700 mode applies ONLY to the final leaf directory (/opt/app/data/secrets). Any missing intermediate parent directories (/opt/app and /opt/app/data) are created using the process's default umask modified by u+wx (typically 0755) so they remain traversable.

Advertisement

If you need restricted permissions on every level of a newly created parent hierarchy, either create each sensitive parent explicitly with its own -m flag or adjust the shell's umask (e.g., (umask 0077 && mkdir -p /opt/app/data/secrets)) inside a subshell.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Create a Single Directory or Multiple Peer Directories at Once

Pass multiple directory names separated by spaces along with the -v (verbose) flag to create several directories in a single command.

mkdir -v backups logs tmp

# Illustrative output (reviewed against documentation)
mkdir: created directory 'backups'
mkdir: created directory 'logs'
mkdir: created directory 'tmp'

Passing multiple operands avoids invoking separate processes in a loop and confirms each directory creation on stdout when -v is active.

2. Create a Deeply Nested Directory Tree Idempotently with -p

Use the -p (--parents) flag to build a multi-level directory hierarchy in one step, automatically creating any missing intermediate parent folders.

mkdir -pv /tmp/releases/2026-10/artifacts/checksums

# Illustrative output (reviewed against documentation)
mkdir: created directory '/tmp/releases'
mkdir: created directory '/tmp/releases/2026-10'
mkdir: created directory '/tmp/releases/2026-10/artifacts'
mkdir: created directory '/tmp/releases/2026-10/artifacts/checksums'

If you run the exact same command a second time, mkdir -pv exits cleanly with status 0 and prints nothing because all directories in the chain already exist—making -p mandatory for idempotent shell scripts.

3. Create a Private Directory with Strict Permissions Atomically Using -m

Use the -m flag to assign 0700 (drwx------) permissions at the exact moment of inode creation rather than running mkdir followed by chmod.

mkdir -vm 0700 ~/.ssh
ls -ld ~/.ssh

# Illustrative output (reviewed against documentation)
mkdir: created directory '/home/sysadmin/.ssh'
drwx------ 2 sysadmin sysadmin 4096 Oct 22 10:15 /home/sysadmin/.ssh

Creating a sensitive directory with default 0755 permissions and then tightening it with chmod 0700 leaves a brief race window where another local user can open a file descriptor inside the directory. Using mkdir -m 0700 eliminates that window completely.

4. Scaffold a Complete Project Hierarchy with Bash Brace Expansion

Combine mkdir -pv with Bash curly-brace expansion ({...}) to generate a full multi-tier microservice repository layout in a single command.

mkdir -pv /tmp/webapp/{src/{api,models,middleware},config/{dev,staging,prod},tests/{unit,integration},docs}

# Illustrative output (reviewed against documentation)
mkdir: created directory '/tmp/webapp'
mkdir: created directory '/tmp/webapp/src'
mkdir: created directory '/tmp/webapp/src/api'
mkdir: created directory '/tmp/webapp/src/models'
mkdir: created directory '/tmp/webapp/src/middleware'
mkdir: created directory '/tmp/webapp/config'
mkdir: created directory '/tmp/webapp/config/dev'
mkdir: created directory '/tmp/webapp/config/staging'
mkdir: created directory '/tmp/webapp/config/prod'
mkdir: created directory '/tmp/webapp/tests'
mkdir: created directory '/tmp/webapp/tests/unit'
mkdir: created directory '/tmp/webapp/tests/integration'
mkdir: created directory '/tmp/webapp/docs'

Do not put unquoted spaces after commas inside the braces ({api,models}, not {api, models}) or wrap the braces in quotes, because brace expansion is performed by Bash before invoking mkdir.

5. Create a Shared Team Directory with Setgid Inheritance

Use symbolic or 4-digit octal mode syntax with -m (such as 2775 or u=rwx,g=rwxs,o=rx) to enable the setgid bit so all newly created files inside inherit the directory's group.

sudo mkdir -vm 2775 /srv/engineering-shared
sudo chown :devops /srv/engineering-shared
ls -ld /srv/engineering-shared

# Illustrative output (reviewed against documentation)
mkdir: created directory '/srv/engineering-shared'
drwxrwsr-x 2 root devops 4096 Oct 22 11:20 /srv/engineering-shared

Notice the 's' in the group execute slot (rws): any file or subdirectory created inside /srv/engineering-shared by any team member will automatically belong to the devops group rather than the user's personal primary group.

6. Provision a System Directory with SELinux Policy Labeling (-Z)

On RHEL, Rocky Linux, AlmaLinux, or Fedora systems enforcing SELinux, pass -Z so mkdir consults the system file_contexts database and labels the new directory appropriately.

sudo mkdir -pZ /var/www/html/static-assets
ls -ldZ /var/www/html/static-assets

# Illustrative output (reviewed against documentation)
drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_sys_content_t:s0 4096 Oct 22 11:45 /var/www/html/static-assets

Ensuring the httpd_sys_content_t SELinux type is applied at creation time prevents 403 Forbidden errors in Nginx or Apache caused by unlabeled or mislabeled parent directories.

Real-World Workflows, Pipelines, and Shell Automation

Atomic Mutex Lock Acquisition in Cron and Backup Scripts

Because the kernel mkdir(2) syscall without -p is guaranteed to be atomic across local POSIX filesystems, use mkdir to build a reliable, dependency-free mutex lock that prevents overlapping cron job executions.

#!/usr/bin/env bash
set -euo pipefail

LOCK_DIR="/var/lock/nightly-db-backup.lock"

if mkdir "${LOCK_DIR}" 2>/dev/null; then
  trap 'rm -rf "${LOCK_DIR}"' EXIT INT TERM
  echo "$$" > "${LOCK_DIR}/pid"
  echo "[INFO] Lock acquired by PID $$. Starting backup..."
else
  HOLDER_PID=$(cat "${LOCK_DIR}/pid" 2>/dev/null || echo "unknown")
  echo "[WARN] Backup already running under PID ${HOLDER_PID}. Exiting." >&2
  exit 0
fi

# Illustrative output (reviewed against documentation)
[INFO] Lock acquired by PID 48219. Starting backup...

Unlike testing for a lock file with [ ! -f lockfile ] && touch lockfile—which suffers from a race condition between test and touch—mkdir without -p succeeds for only one process in the kernel VFS.

Date-Partitioned Log and Artifact Archival Pipeline

Automatically generate year/month/day partitioned archive directories using date command substitution and move rotated logs into the target path.

ARCHIVE_ROOT="/var/backups/app-logs/$(date -u +%Y/%m/%d)"
sudo mkdir -pv -m 0750 "${ARCHIVE_ROOT}"
ls -ld "${ARCHIVE_ROOT}"

# Illustrative output (reviewed against documentation)
mkdir: created directory '/var/backups/app-logs/2026'
mkdir: created directory '/var/backups/app-logs/2026/10'
mkdir: created directory '/var/backups/app-logs/2026/10/22'
drwxr-x--- 2 root root 4096 Oct 22 12:00 /var/backups/app-logs/2026/10/22

Using UTC date formatting (date -u +%Y/%m/%d) with mkdir -p ensures daily archival jobs seamlessly roll over across month and year boundaries without manual intervention.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding mkdir inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

When creating temporary working directories in shell scripts under world-writable paths like /tmp or /var/tmp, avoid using mkdir /tmp/myscript-$$ with predictable PID names, as local attackers can pre-create symlinks or directories to stage symlink or hijacking attacks. Prefer mktemp -d for temporary workspaces, or if using mkdir, omit -p so the script aborts immediately if the directory already exists, and always pass -m 0700.

Additionally, remember that directory execute permission (x) in Linux controls traversal (the ability to cd into the directory or access files inside it by name), whereas read permission (r) controls listing directory contents (readdir). Setting -m 0711 on a parent directory allows users to access a known subdirectory inside it without being able to enumerate peer subdirectories.

GNU/Linux, BSD, and BusyBox Implementation Differences

The core flags -p (--parents) and -m (--mode) are strictly mandated by POSIX.1-2017 and behave identically across GNU/Linux, FreeBSD, OpenBSD, NetBSD, macOS, and Alpine BusyBox.

However, the -v (--verbose) flag and long options (--parents, --mode) are GNU/BSD extensions that may not exist on strict legacy POSIX or Solaris implementations, and the -Z / --context flags are specific to Linux distributions compiled with SELinux or SMACK support. Furthermore, curly-brace expansion ({a,b,c}) is a feature of Bash, Zsh, and Ksh—not the mkdir binary itself—so scripts starting with #!/bin/sh (which runs dash on Debian/Ubuntu) will treat {a,b} as a literal directory name instead of expanding it.

Troubleshooting Common Errors and Diagnostics

mkdir: cannot create directory '/opt/data/logs': No such file or directory

Root Cause: One or more intermediate parent directories (/opt or /opt/data) do not exist yet, and mkdir was invoked without the -p flag.

Resolution: Add the -p (--parents) option so mkdir creates all missing parent directories along the path automatically.

sudo mkdir -p /opt/data/logs

mkdir: cannot create directory 'build': File exists

Root Cause: Either a directory named build already exists and -p was omitted, OR a regular file or broken symlink named build exists at that exact path (even mkdir -p will fail if a non-directory file occupies the target name).

Resolution: Check what occupies the path with ls -ld build. If it is a directory, use mkdir -p build; if a regular file is blocking the directory name, rename or remove the conflicting file first.

ls -ld build
mkdir -p build

mkdir: cannot create directory '/var/lib/app': No space left on device

Root Cause: Either the filesystem has exhausted all free data blocks (df -h) OR it has exhausted all available inodes (df -i), which prevents allocating a new directory inode even when gigabytes of disk space remain.

Resolution: Check both block usage and inode exhaustion using df -h and df -i on the target mount point, and clean up orphaned temporary files or small cache files.

df -h /var/lib
df -i /var/lib

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
The -p (--parents) flag instructs mkdir to create any missing intermediate parent directories along the specified path and to exit with status 0 (no error) if the target directory already exists. This makes mkdir -p safe to run repeatedly in automation scripts.
Brace expansion ({src,tests}) is performed by the shell, not by mkdir. It fails and creates a literal folder with braces in two situations: if you wrapped the path in quotes (mkdir "project/{src,tests}"), or if your script runs under /bin/sh (dash) instead of /bin/bash. Remove quotes around the braces and use #!/usr/bin/env bash.
By default, mkdir requests mode 0777 from the kernel, and the kernel subtracts your shell's active umask (typically 0022). Subtracting 0022 from 0777 leaves 0755 (rwxr-xr-x). To override the umask for a specific directory, pass the -m flag, such as mkdir -m 0700 secret_dir.
Wrap the entire directory name in double or single quotes—for example, mkdir "Project Assets 2026"—or escape each space with a backslash (mkdir Project\ Assets\ 2026). Without quotes or escaping, mkdir will create three separate directories named Project, Assets, and 2026.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout