- mkdir cannot create directory
- mkdir: cannot create directory – File exists
- Possible solutions to mkdir: cannot create directory – file exists scenario
- Rename (move) existing directory
- Remove existing file
- mkdir: cannot create directory – Permission denied
- Ошибка: mkdir — Cannot Create Directory
- mkdir: cannot create directory – File exists
- Возможные решения проблем mkdir: cannot create directory
- Сценарий file exists
- Переименовать (или переместить) существующий файл
- Удалить существующий файл
- Как создавать каталоги в Linux (команда mkdir)
- Синтаксис команды Linux mkdir
- Как создать новый каталог
- Как создать родительские каталоги
- Как установить разрешения при создании каталога
- Как создать несколько каталогов
- Выводы
- mkdir: cannot create directory ‘a’: Permission denied #4836
- Comments
- xzn commented Jan 22, 2020
- sirredbeard commented Feb 15, 2020
- xzn commented Feb 16, 2020
- sirredbeard commented Feb 18, 2020
- xzn commented Feb 18, 2020
- sirredbeard commented Feb 18, 2020
- xzn commented Feb 18, 2020
- ikastro commented Mar 3, 2020
- WMLHUST commented May 8, 2020
- kudaba commented Jun 1, 2020
- kudaba commented Sep 25, 2020
- stu85010 commented Oct 15, 2020
- kudaba commented Dec 4, 2020
- EmilySeville7cfg commented Apr 16, 2021 •
- mkdir: cannot create directory ‘/bitnami/postgresql/data’: Permission denied #1210
- Comments
- docktermj commented May 29, 2019 •
- docktermj commented May 29, 2019
- docktermj commented May 29, 2019
- javsalgar commented May 30, 2019
- docktermj commented May 31, 2019
- docktermj commented May 31, 2019 •
- docktermj commented May 31, 2019
- docktermj commented May 31, 2019
- docktermj commented May 31, 2019
- docktermj commented May 31, 2019
- docktermj commented Jun 1, 2019
- javsalgar commented Jun 3, 2019
- docktermj commented Jun 11, 2019
- mirekphd commented Aug 23, 2020
mkdir cannot create directory
New Linux users often get puzzled by the “mkdir: cannot create directory” errors when taking first steps and trying to learn basics of working with files and directories. In this short post I’ll show the two most common types of this mkdir error and also explain how to fix things so that you no longer get these errors.
mkdir: cannot create directory – File exists
This should be self explanatory after a few weeks of using commands like mkdir, but the first time you see this it can be confusing.
File exists? How can it be when you’re just trying to create a directory? And why does it say “File exists” when you’re trying to create a directory, not a file?
This error suggests that the directory name you’re using (/tmp/try in my example shown on the screenshot) is already taken – there is a file or a directory with the same name, so another one can’t be created.
Consider this scenario:
You can use the wonderful ls command to check what’s going on:
Sure enough, we have a directory called /tmp/try already!
The reason it says “File exists” is because pretty much everything in Unix is a file. Even a directory!
Possible solutions to mkdir: cannot create directory – file exists scenario
Rename (move) existing directory
Use the mv command to move /tmp/try into some new location (or giving it new name). Here’s how to rename /tmp/try into /tmp/oldtry:
Let’s rerun the mkdir command now:
…and since there are no errors this time, we probably have just created the /tmp/try directory, as desired. Let’s check both /tmp/try and the /tmp/oldtry with ls:
Remove existing file
Another option you always have is to simply remove the file that’s blocking your mkdir command.
First, let’s create an empty file called /tmp/newtry and confirm it’s a file and not a directory usng ls command:
Now, if we try mkdir with the same name, it will fail:
So, to fix the issue, we remove the file and try mkdir again:
This time there were no errors, and ls command can show you that indeed you have a directory called /tmp/newtry now:
mkdir: cannot create directory – Permission denied
This is another very common error when creating directories using mkdir command.
The reason for this error is that the user you’re running the mkdir as, doesn’t have permissions to create new directory in the location you specified.
You should use ls command on the higher level directory to confirm permissions.
Let’s proceed with an example:
All of these commands succeeded because I first created new directory called try2018, then another subdirectory inside of it. ls command confirmed that I have 775 permissions on the try2018 directory, meaning I have read, write and execture permissions.
Now, let’s remove the write permissions for everyone for directory try2018:
If I try creating a subdirectory now, I will get the mkdir: cannot create directory – permissions denied error:
To fix the issue, let’s add write permissions again:
As you can see, try2018/yetanotherone directory was successfully created:
That’s it for today! Hope you liked this tutorial, be sure to explore more basic Unix tutorials on my blog.
See Also Basic Unix commands mkdir command in Unix File types in Unix chmod and chown Unix commands tutorial
Источник
Ошибка: mkdir — Cannot Create Directory
Новички в Linux часто не понимают, что делать при получении ошибки “mkdir: cannot create directory” во время работы с командной строкой. Есть несколько причин возникновения такой ошибки, и в этом переводе своей англоязычной статьи с сайта Unix Tutorial я покажу эти причины и их устрание на примерах.
mkdir: cannot create directory – File exists
В переводе с английского сообщение означает: невозможно создать каталог — файл уже существует.
ФАЙЛ существует? А при чём тут проблема создания каталога? И почему ошибка говорить “существует файл”, когда мы вообще пытаемся создавать каталог, а не файл?
На самом деле всё просто: большинство объектов в Linux являются файлами и структурами в файловой системе. Поэтому эта ошибка означает, что там, где вы пытаетесь выполнить команду создания нового каталога, уже существует другой объект с таким же именем. В данном случае — это файл, а не каталог. Но у файла такое же имя, как у желаемого каталога, так что создать второй объект с таким же именем не получится.
намекает, что у нас уже есть файл с именем /tmp/try.
Очень просто проверить эту гипотезу с помощью команды ls:
Так и есть, у нас существует файл с таким именем.
Возможные решения проблем mkdir: cannot create directory
Сценарий file exists
Если файл с таким именем уже существует, а каталог всё же очень хочется создать, то есть решения.
Переименовать (или переместить) существующий файл
Используем команду mv для перемещения /tmp/try в другой каталог (или просто сменим имя try на другое, оставив файл в том же каталоге /tmp). Вот как можно переименовать файл в имя oldtry:
Теперь давайте попробуем ту же команду mkdir:
…и всё замечательно работает! Никаких ошибок, и создался новый каталог под названием /tmp/try. Подтверждаем это с помощью команды ls:
Удалить существующий файл
Ещё одна опция, которая напрашивается сама собой — можно просто удалить неугодный файл, который мешает созаднию нашего нового каталога.
Для этого примера создадим новый пустой файл с названием /tmp/newtry
Если попробовать mkdir, то получится ожидаемая ошибка:
А теперь мы просто удалим неугодный файл и попробуем mkdir снова:
В этот раз нет никаких ошибок, всё снова сработало:
##mkdir: cannot create directory – Permission denied
Это — ещё один распространённый сценарий при создании каталогов.
В переводе на русский, сообщение говорит: невозможно создать каталог — недостаточно прав доступа. То есть файлов с таким же именем нет, но текущий пользователь, под которым мы пытаемся создать каталог, не имеет прав в текущем месте файловой системы для создания новых каталогов (и файлов).
Основной подход к такой ошибке — проверка прав доступа в каталоге, где получена ошибка. Команда ls и здесь поможет. You should use ls command on the higher level directory to confirm permissions.
Все эти команды сработали без ошибок, и ls показывает, что у меня есть полные права доступа к каталогу try2018 — rwx для меня, rwx для моей группы и r-x для всех остальных (это я читаю фрагмент drwxrwxr-x в строке с try2018).
Теперь давайте уберём права на запись (и создание новых объектов) в каталоге try2018:
Теперь мои права к этому каталогу сменились с полных (rwx — read/write/execute) на только чтение (r-x — read/execute). Так что если я попробую создать в try2018 какой-то подкаталог, выйдет та самая ошибка про недостаток прав доступа:
Чтобы исправить проблему, нужно исправить права доступа на каталоге, где мы видим ошибку. И пробуем mkdir снова:
Вот теперь — порядок, всё создалось,
На сегодня — всё! Будут ещё вопросы по самым основам Linux — обращайтесь!
Источник
Как создавать каталоги в Linux (команда mkdir)
В системах Linux вы можете создавать новые каталоги либо из командной строки, либо с помощью файлового менеджера вашего рабочего стола. Команда, позволяющая создавать каталоги (также известные как папки), — это mkdir .
В этом руководстве рассматриваются основы использования команды mkdir , включая повседневные примеры.
Синтаксис команды Linux mkdir
Синтаксис команды mkdir следующий:
Команда принимает в качестве аргументов одно или несколько имен каталогов.
Как создать новый каталог
Чтобы создать каталог в Linux, передайте имя каталога в качестве аргумента команды mkdir . Например, чтобы создать новый каталог newdir вы должны выполнить следующую команду:
Вы можете убедиться, что каталог был создан, перечислив его содержимое с помощью команды ls :
При указании только имени каталога без полного пути он создается в текущем рабочем каталоге.
Текущий рабочий каталог — это каталог, из которого вы запускаете команды. Чтобы изменить текущий рабочий каталог, используйте команду cd .
Чтобы создать каталог в другом месте, вам необходимо указать абсолютный или относительный путь к файлу родительского каталога. Например, чтобы создать новый каталог в каталоге /tmp вы должны ввести:
Если вы попытаетесь создать каталог в родительском каталоге, в котором у пользователя недостаточно прав, вы получите сообщение об ошибке Permission denied :
Параметр -v ( —verbose ) указывает mkdir печатать сообщение для каждого созданного каталога.
Как создать родительские каталоги
Родительский каталог — это каталог, который находится над другим каталогом в дереве каталогов. Чтобы создать родительские каталоги, используйте параметр -p .
Допустим, вы хотите создать каталог /home/linuxize/Music/Rock/Gothic :
Если какой-либо из родительских каталогов не существует, вы получите сообщение об ошибке, как показано ниже:
Вместо того, чтобы создавать недостающие родительские каталоги один за другим, вызовите команду mkdir с параметром -p :
Когда используется опция -p , команда создает каталог, только если он не существует.
Если вы попытаетесь создать каталог, который уже существует, а параметр -p не mkdir , mkdir выведет сообщение об ошибке File exists :
Как установить разрешения при создании каталога
Чтобы создать каталог с определенными разрешениями, используйте параметр -m ( -mode ). Синтаксис для назначения разрешений такой же, как и для команды chmod .
В следующем примере мы создаем новый каталог с разрешениями 700 , что означает, что только пользователь, создавший каталог, сможет получить к нему доступ:
Когда опция -m не используется, вновь созданные каталоги обычно имеют права доступа 775 или 755 , в зависимости от значения umask .
Как создать несколько каталогов
Чтобы создать несколько каталогов, укажите имена каталогов в качестве аргументов команды, разделенные пробелом:
Команда mkdir также позволяет создать сложное дерево каталогов с помощью одной команды:
Приведенная выше команда создает следующее дерево каталогов :
Выводы
Команда mkdir в Linux используется для создания новых каталогов.
Для получения дополнительной информации о mkdir посетите страницу руководства mkdir .
Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.
Источник
mkdir: cannot create directory ‘a’: Permission denied #4836
Comments
xzn commented Jan 22, 2020
Cannot create directory with mkdir even though touch , rm , rmdir , mv all works fine.
Microsoft Windows [Version 10.0.19546.1000]
Arch Linux distro created with
wsl —export Arch D:\arch.tar
wsl —import Arch2 D:\WSL\Arch2 D:\arch.tar —version 2
cd /mnt/d/
mkdir a
gives
mkdir: cannot create directory ‘a’: Permission denied
Works fine at home directory though
cd /mnt/c/Users/user
mkdir a
no problem here.
Where should I start to look for a solution for this?
The text was updated successfully, but these errors were encountered:
sirredbeard commented Feb 15, 2020
Can you reproduce this when using C:\ instead?
xzn commented Feb 16, 2020
sirredbeard commented Feb 18, 2020
Where did you get your Arch image?
I have tried the one at https://github.com/yuk7/ArchWSL/releases and except for some issues with permissions on the package GPG signatures it worked well for me.
xzn commented Feb 18, 2020
WSL works fine, exporting it to WSL2 and I have trouble with mkdir .
Will try your link for now.
sirredbeard commented Feb 18, 2020
Give the other Arch image a try, I know it’s a good image.
What are the permissions in the folder what you are trying to create a folder?
Have you tried chown?
xzn commented Feb 18, 2020
chown, chmod all works alongside touch, rm, rmdir, mv, etc. I just noticed mkdir wouldn’t work when git clone gives me permission denied.
Thanks for helping btw! Will try a clean image instead of exporting from one I currently have.
ikastro commented Mar 3, 2020
I have the same issue, I am trying to create a directory so that I can mount the drive
WMLHUST commented May 8, 2020
I delete a git dict in windows explorer, then mkdir failed in WSL terminal.
kudaba commented Jun 1, 2020
I just upgraded to ubuntu version 2 and I’m getting the same issue. I can’t mkdir on my drives in /mnt/c and /mnt/d, but it works fine in my home folder and other areas. All other operations work fine. Even running with sudo doesn’t help. My app that I’m working on also can’t create folders.
kudaba commented Sep 25, 2020
In my case it was a mount issue, or at least changing the mount options fixed it. Running the following command from https://devblogs.microsoft.com/commandline/chmod-chown-wsl-improvements/ worked for me:
sudo umount /mnt/c && sudo mount -t drvfs C: /mnt/c -o metadata
It’s unclear but the command seems to be permanent. I’m not sure what happened during the upgrade from WSL 1 to 2 that affected this.
stu85010 commented Oct 15, 2020
In my case, this issue was solved by: giving the Full control permission to your Windows account for this directory with Security tab
Said, I’d created a directory at /c/src and trying to develop there, but the «User» group doesn’t have Full control permission at that path, so the folder creation is failed in WSL in my case.
Then I was added the Full control permission to my Windows account at that folder, and the mkdir worked perfectly in that directory.
kudaba commented Dec 4, 2020
Turns out my mount solution didn’t last through a reboot, but the Full Control to users fixed it, thanks @stu85010.
EmilySeville7cfg commented Apr 16, 2021 •
I have the same issue on Ubuntu 20.04.2 LTS. Besides other commands like touch and I/O redirection fail with the same error. Why it happens?
Источник
mkdir: cannot create directory ‘/bitnami/postgresql/data’: Permission denied #1210
Comments
docktermj commented May 29, 2019 •
Which chart:
Description
Although creating the bitnami/postgresql chart worked a few weeks ago in minikube , recently it has begun failing with the following error:
Steps to reproduce the issue:
- Contents of namespace.yaml file:
- Contents of persistent-volume-postgresql.yaml file:
- Contents of persistent-volume-claim-postgresql.yaml file
- Create persistent volume claim:
- Contents of postgresql.yaml file:
- Install bitnami/postgresql helm chart.
Describe the results you received:
Describe the results you expected:
A chart that comes up. 🙂
Additional information you deem important (e.g. issue happens only occasionally):
Version of Helm and Kubernetes:
The text was updated successfully, but these errors were encountered:
docktermj commented May 29, 2019
docktermj commented May 29, 2019
javsalgar commented May 30, 2019
I see that you manually created a PVC using hostpath. In that case, the permissions may be incorrect due to the non-root nature of the container. Could you try not creating the PVC instead?
docktermj commented May 31, 2019
docktermj commented May 31, 2019 •
/bitnami/postgresql/data was introduced in upstreamed/postgresql/values.yaml 22 days ago (Around May 9, 2019) in the following commit:
docktermj commented May 31, 2019
Well I thought configuring minikube ‘s mount point would help. It gets me further, but yet another roadblock:
Results (after running commands in original issue description):
docktermj commented May 31, 2019
@javsalgar, Unfortunately running without a PVC is a non-starter. The demonstration I’m creating needs to illustrate the use of PV and PVC. We anticipate customers wanting to try it out on minikube and then use «real» PV/PVC on their production Kubernetes.
We’re delighted with Bitnami Docker images and Helm charts, we don’t want to highlight any short-comings with them. So I’m looking for a straight-forward way of illustrating the use of Bitnami charts for PostgreSQL (and RabbitMQ) in a minikube environment.
docktermj commented May 31, 2019
Although it doesn’t help me get where I want to go, If I change the contents of postgresql.yaml to
That is persistence.enabled: false . It works. But that doesn’t get me what I need.
docktermj commented May 31, 2019
. what gets me is that this chart and the RabbitMQ chart were working about a month ago in minikube . So this issue concerns something that changed in the last month.
docktermj commented Jun 1, 2019
javsalgar commented Jun 3, 2019
I saw that you opened an issue in helm/charts#14390. Let’s continue the conversation there.
docktermj commented Jun 11, 2019
mirekphd commented Aug 23, 2020
@docktermj : incorrect ownership of ‘/bitnami/postgresql/data’ is a more generic problem, not specific to Helm charts, so I’d rather re-open the issue if you can, if only to correct the volumes documentation on Docker Hub overview page to incorporate my solution I found here.
It has just resurfaced for bitnami/postgres:12 in our Openshift 3.11 cluster with data persistence provided by PVCs mapped to local NFS.
If I set mountPath to /bitnami/postgresql or /bitnami/postgresql/data , I still get the error. The message (printed in application logs only when I set BITNAMI_DEBUG=»true» ) is just as the OP reported:
See error log details
However, if I move the mountPath up one level to /bitnami/ , then bitnami/postgresql:12 container starts correctly:
Источник