mkdir -p -m only sets permissions on the final directory

`mkdir -p -m 700 a/b/c` only chmods `c` — intermediate `a` and `b` use the umask.

Problem

`mkdir -p` creates intermediate directories with the current umask, and only applies `-m` to the leaf. If you need restrictive permissions on the whole chain (a sensitive cache path, for example), the intermediate dirs stay world-readable.

Bad

mkdir -p -m 700 /var/lib/myapp/secrets

Good

mkdir -p /var/lib/myapp/secrets
chmod 700 /var/lib/myapp /var/lib/myapp/secrets

# Or set umask before mkdir:
(umask 077 && mkdir -p /var/lib/myapp/secrets)

Explanation

The umask form is concise and avoids a window where the directory exists with loose permissions. Use it when creating any path that will hold credentials, tokens, or PII.

When It Matters

mkdir -p -m 700 a/b/c applies the mode only to the final component. Intermediate directories a and a/b are created with the default mode derived from the umask, which on most systems means world-readable. If the point of the 700 was to protect secrets, the parent directories leak the tree structure and possibly more. This matters most in exactly the code that uses restrictive modes: key stores, credential caches, and per-user state directories under a shared path.

Second Example

Note

The umask approach is race-free: the directories are never briefly world-readable between creation and chmod.

Exceptions

When every parent already exists, -m applies to the one directory actually created and there is nothing ambiguous about it. The warning is only meaningful when -p may create intermediate levels; if you know it cannot, disable it on the line with a comment saying so.

Faq

Q

Does mkdir -p fail if the directory exists?

A

No, that is its purpose. It also does not change the mode of a directory that already exists, so -m is silently ignored in that case.

Q

Is chmod after mkdir a security race?

A

Briefly, yes: between the two calls the directory carries the umask-derived mode. Setting umask before mkdir avoids the window entirely.

Q

How does umask relate to -m?

A

The mode given with -m is applied literally, without umask filtering, to the final directory. Directories created implicitly by -p get the default mode filtered through the umask.