Skip to content

/errors/coreutils/mkdir-cannot-create-directory-file-exists

mkdir: cannot create directory 'dir': File exists

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · ls (GNU coreutils) 8.32updated
tool
GNU coreutils
exit code
1
versions
GNU coreutils 8.x – 9.x
os
linux, macos, windows

mkdir: cannot create directory 'build': File exists means something named build is already there. If it is a directory and you only need it to exist, use mkdir -p build, which does nothing and exits 0 when the directory is present. If it is a file, -p does not help: rename or remove the file first. The underlying system call fails with EEXIST, and mkdir exits with status 1.

Reproduce the error

bash
mkdir build
mkdir build

Output · exit 1

mkdir: cannot create directory ‘build’: File exists

Fix: mkdir -p for "create if missing"

-p creates missing parents and treats an existing directory as success, so the command is safe to run repeatedly:

bash
mkdir -p build/out
mkdir -p build/out
echo "exit status: $?"

Output

exit status: 0

When a file has the same name

-p only accepts an existing directory. A regular file with the same name still fails, with the same message:

bash
touch build
mkdir -p build

Output · exit 1

mkdir: cannot create directory ‘build’: File exists

Check what the entry is before deciding what to do:

bash
touch build
[ -d build ] && echo "directory" || echo "not a directory"
ls -l build | cut -c1

Output

not a directory
-

A - in the first column is a regular file, l a symlink, d a directory. A symlink to a directory counts as an existing directory for mkdir -p.

  • mkdir: cannot create directory 'x': Permission denied: the parent directory is not writable by your user.
  • mkdir: cannot create directory 'a/b': No such file or directory: a parent is missing; add -p.
  • ln: failed to create symbolic link 'l': File exists: the same EEXIST condition for links; ln -sfn replaces the link.

Sources