mkdir
Overview
mkdir (make directory) creates new directories. With -p it creates parent paths as needed and does not error if the target already exists — the workhorse flag for scripts. Optional -m sets the mode for the created directory (subject to umask unless you understand the interaction).
Syntax
mkdir [options] directory...Common Options
| Option | Description |
|---|---|
-p, --parents |
Create parents; no error if existing |
-m MODE, --mode=MODE |
Set permission mode (e.g. 750, u+rwx) |
-v, --verbose |
Print a line for each created directory |
-Z |
Set SELinux context (when SELinux enabled) |
--context=CTX |
Set complete SELinux context |
Key Use Cases
- Create project and deploy directory trees
- Idempotent path ensure in scripts (
-p) - Create with restrictive permissions (
-m 700) - Batch-create sibling dirs with braces
- Scaffold log/cache layouts
Examples with Explanations
Basics
mkdir project
mkdir dir1 dir2 dir3
mkdir -v newdirParents
mkdir -p parent/child/grandchild
mkdir -p /var/lib/myapp/{data,cache,logs}mkdir -p is safe to re-run: existing directories are left alone.
Permissions
mkdir -m 755 public_dir
mkdir -m 700 private_dir
mkdir -m 750 secure_dir
# mode applies to the leaf created; with -p, behavior for parents is version-specific —
# set explicitly if parents need special modes:
mkdir -p -m 755 /srv/app
chmod 750 /srv/appBrace expansion scaffolds
mkdir -p logs/{app,nginx,db}
mkdir -p src/{cmd,internal,pkg} docs scriptsScript: ensure writable data dir
#!/usr/bin/env bash
set -euo pipefail
DATA_DIR=${DATA_DIR:-/var/lib/myapp}
mkdir -p "$DATA_DIR"
chmod 750 "$DATA_DIR"SELinux (when relevant)
mkdir -Z /srv/webdata
# or restorecon after create on labeled systemsParallel with install
install -d -m 755 /opt/myapp/bin
install -d -m 700 /opt/myapp/secretsinstall -d is often preferred in packaging for explicit modes.
Failure cases
mkdir /proc/foo # typically fails (pseudo-fs / perms)
mkdir /existing/file/sub # fails if component is a fileNotes / Pitfalls
- Without
-p, existing directory → error; missing parent → error. - umask affects final mode when you don’t fully specify bits; verify with
stat -c %a dir. - Race in concurrent scripts: two
mkdirwithout-pcan fail; prefer-pfor idempotency. - Creating under sticky dirs (
/tmp) is fine; deleting others’ dirs there is not. - NFS root_squash: creating as root may result in
nobodyownership.
2026-relevant notes
- In containers, create runtime dirs in entrypoints with
-prather than baking empty layers unless needed for ownership. - systemd
RuntimeDirectory=/StateDirectory=can replace hand-rolledmkdirin unit files — prefer unit directives for services. - Immutable systems may only allow mkdir on writable mounts (
/var,/home,/tmp).
Additional Resources
man mkdir- GNU coreutils — mkdir