mkdir -p fails when directory exists
Solution 1
This could be caused if there is already a file by the same name located in the directory.
Note that a directory cannot contain both a file and folder by the same name on linux machines.
Solution 2
Check to see if there is a file (not a directory) with a name same as $directory.
Solution 3
mkdir -p won't create directory if there is a file with the same name is existing in the same directory. Otherwise it will work as expected.
Solution 4
Was your directory a FUSE-based network mount by any chance?
In addition to a file with that name already existing (other answer), this can happen when a FUSE process that once mounted something at this directory crashed (or was killed, e.g. with kill -9
or via the Linux OOM killer).
To see what is happening in detail, run strace -fy mkdir -p $directory
, which shows all syscalls involved and their return values.
I consider the error messages emitted in this case a bug in mkdir -p
(in particular the gnulib
library):
When you run it on a dir that had a FUSE process mounted but that process crashed, it says
mkdir: cannot create directory ‘/mymount’: File exists
which is rather highly inaccurate, because the underlying stat()
call returns ENOTCONN (Transport endpoint is not connected)
; but mkdir
propagates up the less-specific error from the previous mkdir()
sycall.
It's extra confusing because the man page says:
-p, --parents
no error if existing, make parent directories as needed
so it shouldn't error if the dir exists, yet ls -l /
shows:
d????????? ? ? ? ? ? files
so according to this (d
), it is a directory, but it isn't according to test -d
.
I believe a better error message (which mkdir -p
should emit in this case) would be:
mkdir: cannot create directory ‘/mymount’: Transport endpoint is not connected
![UmNyobe](https://i.stack.imgur.com/mrljv.png?s=256&g=1)
UmNyobe
If you see me answer on the topic of c++ templates then my account has probably been hacked. update: I have been assimilated by the template freaks. For the laugh : https://twitter.com/isotrumpp
Updated on January 19, 2021Comments
-
UmNyobe over 3 years
On one of our remote systems
mkdir -p $directory
fails when the directory exists. which means it showsmkdir: cannot create directory '$directory' : file exists
This is really puzzling, as I believed the contract of
-p
was that is always succeed when the directory already exists. And it works on the other systems I tried.there is a user
test
on all of these systems, anddirectory=/home/test/tmp
.