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
| Option | What it does |
|---|---|
-p | create missing parents; an existing directory isn't an error |
-m mode | the new directory's permissions, as in chmod: -m 700, -m u=rwx,g=rx,o=. Set exactly; umask isn't applied |
-v | print 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
| Option | What it does |
|---|---|
-p | after the directory, also remove its parents while they're empty: rmdir -p a/b/c → c, b, a |
-v | print each removal |
--ignore-fail-on-non-empty | don'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
-mtogether with-papplies only to the last directory.mkdir -p -m 700 x/y/zcreatesxandx/ywith umask-based permissions (755), and onlyzwith700.-pdoesn't check that the directory is yours and has the right permissions: if it already existed,mkdir -p -m 700leaves its permissions alone. If you need exact permissions, runchmodseparately.- A file instead of a directory. If a regular file sits on the path, even
-pfails: "cannot create directory 'fi': Not a directory". - Braces are bash, not
mkdir. Insh(dash)mkdir {a,b}creates one directory named{a,b}. A space inside ({a, b}) breaks the expansion in bash too. rmdirdoesn't remove non-empty directories — "Directory not empty". That's a safeguard; for a tree with contents —rm -r.rmdir -pstops at the first non-empty parent and returns1, even though the lower directories have already been removed. In a script add--ignore-fail-on-non-empty.