← Full reference

mkdir

Creating directories — with parents and the right permissions in one go

mkdir creates directories. With -p it creates the whole chain of parents and doesn't complain if the directory already exists — which is why scripts almost always use mkdir -p. Its counterpart is rmdir, which removes empty directories. The sandbox has GNU coreutils 9.4.

Syntax

mkdir [options] directory…
rmdir [options] empty_directory…

Exit code: 0 — everything was created (with -p — or already existed), 1 — error: the directory exists (without -p), no parent, no permissions, a file sits where the path should be.

mkdir options

OptionWhat it does
-pcreate missing parents; an existing directory isn't an error
-m modethe new directory's permissions, as in chmod: -m 700, -m u=rwx,g=rx,o=. Set exactly; umask isn't applied
-vprint each directory created: mkdir: created directory 'a/b'

Without -m, a new directory's permissions are 777 minus the umask (with umask 022 — 755, drwxr-xr-x).

rmdir options

OptionWhat it does
-pafter the directory, also remove its parents while they're empty: rmdir -p a/b/c → c, b, a
-vprint each removal
--ignore-fail-on-non-emptydon't treat a non-empty directory as an error — silently leave it

Examples

# a chain of directories in one command
mkdir -p /srv/app/releases/v1

# several directories via bash brace expansion
mkdir -p project/{src,tests,docs}
mkdir -p logs/{2024,2025}/{01..12}

# a private directory: owner-only access
mkdir -m 700 ~/.secrets

# see what actually gets created
mkdir -pv /srv/data/cache

# in a script: create only if missing, and exit on error
mkdir -p "$OUT_DIR" || exit 1

# remove an empty branch of directories
rmdir -p logs/2024/01

Pitfalls

  • -m together with -p applies only to the last directory. mkdir -p -m 700 x/y/z creates x and x/y with umask-based permissions (755), and only z with 700.
  • -p doesn't check that the directory is yours and has the right permissions: if it already existed, mkdir -p -m 700 leaves its permissions alone. If you need exact permissions, run chmod separately.
  • A file instead of a directory. If a regular file sits on the path, even -p fails: "cannot create directory 'fi': Not a directory".
  • Braces are bash, not mkdir. In sh (dash) mkdir {a,b} creates one directory named {a,b}. A space inside ({a, b}) breaks the expansion in bash too.
  • rmdir doesn't remove non-empty directories — "Directory not empty". That's a safeguard; for a tree with contents — rm -r.
  • rmdir -p stops at the first non-empty parent and returns 1, even though the lower directories have already been removed. In a script add --ignore-fail-on-non-empty.

See also

rm · chmod · umask · chown · mktemp · touch · cp