/errors/coreutils/mkdir-cannot-create-directory-file-exists
mkdir: cannot create directory 'dir': File exists
- 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
mkdir build
mkdir buildOutput · 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:
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:
touch build
mkdir -p buildOutput · exit 1
mkdir: cannot create directory ‘build’: File exists
Check what the entry is before deciding what to do:
touch build
[ -d build ] && echo "directory" || echo "not a directory"
ls -l build | cut -c1Output
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.
Related messages
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 sameEEXISTcondition for links;ln -sfnreplaces the link.