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.
Check to see if there is a file (not a directory) with a name same as $directory.
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.