Команда mkdir Linux
Linux организует свою систему файлов при помощи определенных иерархий. В связи с этим будет накапливаться достаточное количество данных, поскольку объем хранилища постепенно увеличивается. Чтобы упорядочить эти сведения, необходимо создать структуру каталогов.
Одна из самых распространенных ошибок — сохранение информации в базе домашнего каталога (того, в который можно попасть, войдя в систему). В нем и остальных подкаталогах, созданных для организации файлов, выполняется большая часть работы пользователя.
Поступив так, придется потратить огромное количество времени, чтобы найти нужные данные среди множества иных файлов. Команда mkdir (Make Directory) поможет справиться с такого рода проблемой.
Синтаксис
Данная команда позволяет пользователю создать один или более каталогов или подкаталогов с заданными именами и режимом доступа 0077, а также установить на них разрешения.
- -m (—mode=режим) — назначить режим доступа (права). По умолчанию mod принимает значение 0777, что обеспечивает неограниченные права.
- -p (—parents) — не показывать ошибки, а также их игнорировать.
- -z (—context=CTX ) принимает контекст SELinux для каталога по умолчанию.
- -v (—verbose) — выводить сообщение о каждом новым каталоге.
- —help — вывести справочную информацию.
- —version — выводит информацию о текущей версии утилиты.
Выполняя команду, нужно иметь достаточно прав на создание перечня в родительском каталоге, либо же произойдет ошибка. Чтобы их задать в символьном виде или в качестве восьмеричных чисел, нужно убедиться, что весь путь до последнего элемента должен существовать. Затем следует воспользоваться функцией -m (или –mode).
Примеры использования
Чтобы понять как работает утилита mkdir рассмотрим примеры.
Создадим новую папку под названием «newpapka». Для этого напишем команду без аргументов.
Новая папка будет принадлежать фактическому владельцу произведенного процесса. При попытке создать уже существующую результат получится ошибочным.
Создадим несколько папок newpapka2, newpapka3, newpapka4.
mkdir newpapka2 newpapka3 newpapka4
Создадим папку «papka» в «/root/katalog».
Создание родительских каталогов
Родительский каталог — это каталог, в котором находится текущий подкаталог.
Зайдем в папку «primercatalog» с помощью команды «cd».
Создадим папку papka1, в papka1 — papaka2, в papka2 — papka3. Для этого будем использовать аргумент «-p» (игнорировать ошибки).
mkdir -p papka1/papka2/papka3
Для примера воспользуемся аргументом «-m» и предоставим доступ на чтение, запись и выполнение содержимого каталогов.
mkdir -m a=rwx primer
mkdir -m 777 primer
Более подробно о назначении прав можно посмотреть в другой статье chmod.
access mode in mkdir() sys call linux c
I have a portion of code
The newly-created directory looks like
But I wanted it to have write permissions for others, i.e. drw-rw-rw- .
When I try to enter the directory, using cd , I get
If I create it with execute permissions, like this:
I am able to enter directory with cd .
dr-xr-xr-x 2 atg atg 4096 Oct 3 18:02 f
Why is the write permission not set?
still permissions i get is->
Should I change umask? Is there any alterative without doing that?
4 Answers 4
A directory without executable permissions cannot be listed.
In addition to setting umask(0) , create the directory with mode 0777 .
The process’s umask value is masking off the write permissions for non-owners. See https://en.wikipedia.org/wiki/Umask:
In computing, umask is a command that determines the settings of a mask that controls how file permissions are set for newly created files. It also may refer to a function that sets the mask, or it may refer to the mask itself, which is formally known as the file mode creation mask. The mask is a grouping of bits, each of which restricts how its corresponding permission is set for newly created files.
The umask value is global to a process. Thus calling umask() will affect all threads running in the process, along with all child processes spawned after changing the value.
To safely ensure file or directory permissions without impacting the rest of the process, you need to explicitly set the permission with chmod() :
If you really want do change umask() , it’s much better to set it to what you need, then restore it afterward:
Linux mkdir command
On Unix-like operating systems, the mkdir command creates new directories in a file system.
This document covers the GNU/Linux version of mkdir.
Syntax
Options
directory | The name of the directory to be created. If the specified directory does not already exist, mkdir creates it. More than one directory may be specified. |
A specified directory can include path information. For instance, if the current directory is /home/hope, and you’d like to create the directory /home/hope/Documents/writing, you can use the command mkdir Documents/writing. If the Documents folder does not already exist, you should specify the -p option to create it automatically, otherwise the command will fail.
—mode=mode
—parents
—verbose
—context=context
Exit status
mkdir returns an exit status of zero if all operations were successful, or a non-zero exit status if operations failed.
Examples
Create a new directory called myfiles in the current directory.
Create the directory myfiles in your home directory, specified here with a tilde («
to represent your home directory, see tilde expansion in bash.
Create the mydir directory, and set its file mode (-m) so that all users (a) may read (r), write (w), and execute (x) it.
For directories, this means that any user on the system may view («read»), and create/modify/delete («write») files in the directory. Any user may also change to («execute») the directory, for example with the cd command.
Same as the above command, but using a numerical file mode. Grants read, write, and execute permissions to the directory for all users. (For more information about file modes, see chmod).
Creates the directory /home/hope/Documents/pdf. If any of the parent directories /home, /home/hope, or /home/hope/Documents do not already exist, they will automatically be created.
How to use mkdir() from sys/stat.h
Problem:
You want to use the mkdir() function from the sys/stat.h POSIX header, but you don’t know what the mode_t argument should look like.
Solution:
For a detailed reference, see the Opengroup page on mkdir
The first argument should be obvious – just enter the path name of the directory you intend to create. If you use a std::string (in C++); use it’s c_str() member function to get a C string.
The second argument defines the permissions the newly created directory shall have. This How-to assumes you’re already familiar with Unix file permissions. If you are not, please read the corresponding Wikipedia Page.
First, decide which rights the directory shall have. This boils down to these 9 questions:
- Shall the owner be able to read/write/execute?
- Shall the group be able to read/write/execute?
- Shall everyone else (= others) be able to read/write/execute? The second argument has the type mode_t , but this is basically just an alias for any type of integer.
sys/stat.h provides you with several integers you can bytewise- OR (|) together to create your mode_t:
- User: S_IRUSR (read), S_IWUSR (write), S_IXUSR (execute)
- Group: S_IRGRP (read), S_IWGRP (write), S_IXGRP (execute)
- Others: S_IROTH (read), S_IWOTH (write), S_IXOTH (execute)
Additionally, some shortcuts are provided (basically a bitwise- OR combination of the above
- Read + Write + Execute: S_IRWXU (User), S_IRWXG (Group), S_IRWXO (Others)
- DEFFILEMODE : Equivalent of 0666 = rw-rw-rw-
- ACCESSPERMS : Equivalent of 0777 = rwxrwxrwx Therefore, to give only the user rwx (read+write+execute) rights whereas group members and others may not do anything, you can use any of the following mkdir() calls equivalently:
In order to grant all rights to everyone (mode 0777 = rwxrwxrwx), you can use any of the following calls equivalently: