- Как создавать каталоги в Linux (команда mkdir)
- Синтаксис команды Linux mkdir
- Как создать новый каталог
- Как создать родительские каталоги
- Как установить разрешения при создании каталога
- Как создать несколько каталогов
- Выводы
- Linux: How to Make a Directory Command
- mkdir command Syntax
- Examples
- How to create a new director
- How to create Directories in Linux
- How to create directories in Linux with verbose option
- Setting up permissions when creating a directory
- Setting up SELinux context with mkdir on RHEL or CentOS
- Sample mkdir demo command
- Summing up
- Getting help
- How to Use ‘mkdir’ to Create Linux Directories
- Make folders from a terminal with this simple command
- What to Know
- How to Create a New Directory
- Change the Permissions of the New Directory
- How to Create a Directory and Set Permissions at the Same Time
- Create a Folder and Any Parents That Are Required
- Get Confirmation That a Directory Was Created
- Ubuntu Documentation
- Understanding and Using File Permissions
- Folder/Directory Permissions
- Permissions in Action
- Changing Permissions
Как создавать каталоги в 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 .
Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.
Источник
Linux: How to Make a Directory Command
H ow do I make directory under Linux operating systems using the command prompt or bash shell?
You need to use the mkdir command to create new folders or directories under Linux operating systems. A directory (also known as folder in MS-Windows/macOS
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | mkdir on Linux |
Est. reading time | 3 mintues |
mkdir command Syntax
The mkdir command has the following syntax:
mkdir dirname
mkdir dirname1 dirname2
mkdir [option] dieNameHere
mkdir -p dir1/dir2/dir3
Examples
Let us see some commann useful examples.
How to create a new director
Open a terminal and then use the mkdir command to create empty directories. The following command would create a directory called foo:
$ mkdir foo
To list directories, enter:
$ ls
$ ls -l
The following command would create two directories within the current directory:
$ mkdir tom jerry
$ ls -l
How to create Directories in Linux
The -p option allows you to create parent directories as needed (if parent do not already exits). For example, you can create the following directory structure:
$ mkdir -p
/public_html/images/trip
Verify it:
ls -l
/public_html/
ls -l
/public_html/images/
ls -R -l
How to create directories in Linux with verbose option
Pass the -v as follows to display a message for each created directory:
mkdir -v dir1
ls -l
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Setting up permissions when creating a directory
To set directory mode (permission) pass the -m option as follows:
mkdir -m
The -m option is same as giving permissions using the chmod command. For examples:
mkdir data
chmod 0700 data
We can do the same with a single command and save typing time at the command-line:
mkdir -v -m 0700 data
ls -ld data
Setting up SELinux context with mkdir on RHEL or CentOS
The syntax is follows to set up system_u:object_r:httpd_sys_content_t:s0 as SELinux context for foo dir:
How to Create a Directory in Linux with mkdir Command with SELinux
Sample mkdir demo command
Animated gif 01: mkdir in action under Linux / Unix like operating systems
Summing up
The mkdir command in Linux is used to make new directories as per your needs. We create a new directory in current directory or given path:
mkdir my-dir-name-here
ls -l
Also make directories recursively which is useful for creating nested dirs on Linux. For instance:
mkdir -p path/to/dir1/dir2
Getting help
Make sure you read the following man pages:
man mkdir
man ls
mkdir —help
Option | Description | Example |
---|---|---|
-m ( —mode=MODE ) | Set file mode (as in chmod command), not a=rwx – umask. | mkdir -m 0644 sales |
-p ( —parents ) | No error if existing, make parent directories as needed. | mkdir -p one/two/three |
-v ( —verbose ) | Print a message for each created directory. | mkdir -v detla |
-Z | Set SELinux security context of each created directory to the default type. | mkdir -Z dir1 |
—context[=CTX] | Like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX. | See above |
—help | Display this help and exit. | mkdir —help |
—version | output version information and exit. | mkdir —version |
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to Use ‘mkdir’ to Create Linux Directories
Make folders from a terminal with this simple command
What to Know
- Open a terminal window in Linux.
- Go to the folder where you want the new directory.
- Enter the command mkdirname of directory.
This article explains how to create directories in Linux with the mkdir command. It also covers the switches used with mkdir and the proper syntax required to make the command work correctly.
How to Create a New Directory
Create new directories in Linux using the command line and the mkdir command.
For example, to create a directory called test, open a terminal window, navigate to the folder where you want the new directory, then enter mkdir test.
Change the Permissions of the New Directory
After creating a new folder, set the permissions so that only a certain user can access it or so that some people can edit files in the folder, but others have read-only permissions.
To continue with the example above, run the ls command to see the permissions for the folder called test:
Run the ls command in the folder where the test folder is located. If it’s your home directory (for example, you didn’t use the cd command), then you don’t have to change the directory here.
You should see something like this (but probably with several other entries, considering that there are other folders there):
The permissions are drwxrwxr-x, 2, owner, and group.
-
- The d indicates that test is a directory.
The first three letters following the d are the owner permissions for the directory specified by the owner’s name:
r is for read. - w is for write.
- x is for execute (which means you can access the folder).
- The d indicates that test is a directory.
- The next three characters are the group permissions for the file specified by the group name. The options are r, w, and x. The hyphen means that a permission is missing. In the example above, anybody belonging to the group can access the folder and see the files, but can’t write to the folder.
- The final characters are the permissions that all users have, and these are the same as the group permissions.
To change the permissions for a file or folder, use the chmod command. The chmod command lets you specify three numbers which set the permissions:
Add the numbers together for a mixture of permissions. For example, to attribute read and execute permissions, the number is 5 (4+1), or for read and write permissions, the number is 6 (4+2).
You must specify three numbers as part of the chmod command. The first number is for the owner permissions, the second is for the group permissions, and the last is for everyone else.
For example, for the owner to have full permissions, the group to have read and execute permissions, and anyone else to have no permissions, enter the following:
Use the chgrp command to change the group name that owns a folder. For example, to create a directory that the accountants in a company can access, first make the group accounts by typing the following:
If you don’t have the correct permission to create a group, use sudo to gain extra privileges or use the su command to switch to an account with valid permissions.
Next, change the group for a folder by typing the following:
To give the owner and everybody else in the accounts group read, write, and execute, but read-only access to others, use the following command:
How to Create a Directory and Set Permissions at the Same Time
You can create a directory and set the permissions for that directory at the same time using the following command:
This command creates a folder that everybody can access. It’s rare to create folders with this kind of permission.
Create a Folder and Any Parents That Are Required
You can create a directory structure without creating each individual folder, for example, to create folders for music as follows:
- /home/music/rock/alicecooper
- /home/music/rock/queen
- /home/music/rap/drdre
- /home/music/jazz/louisjordan
It takes time to create the rock folder for alice cooper and queen, followed by the rap and jazz folders for the others.
By specifying -p, you can create all the parent folders on the fly if these don’t exist:
For example, this mkdir command makes one of the folders listed above:
Get Confirmation That a Directory Was Created
By default, the mkdir command doesn’t tell you if the directory was created successfully. Usually, if no errors are shown, you can assume it worked. However, if you want more verbose output so that you know what’s been created, use the -v switch:
Источник
Ubuntu Documentation
Understanding and Using File Permissions
In Linux and Unix, everything is a file. Directories are files, files are files and devices are files. Devices are usually referred to as a node; however, they are still files. All of the files on a system have permissions that allow or prevent others from viewing, modifying or executing. If the file is of type Directory then it restricts different actions than files and device nodes. The super user «root» has the ability to access any file on the system. Each file has access restrictions with permissions, user restrictions with owner/group association. Permissions are referred to as bits.
To change or edit files that are owned by root, sudo must be used — please see RootSudo for details.
If the owner read & execute bit are on, then the permissions are:
There are three types of access restrictions:
Permission
Action
chmod option
There are also three types of user restrictions:
User
ls output
Note: The restriction type scope is not inheritable: the file owner will be unaffected by restrictions set for his group or everybody else.
Folder/Directory Permissions
Directories have directory permissions. The directory permissions restrict different actions than with files or device nodes.
Permission
Action
chmod option
(view contents, i.e. ls command)
(create or remove files from dir)
(cd into directory)
read restricts or allows viewing the directories contents, i.e. ls command
write restricts or allows creating new files or deleting files in the directory. (Caution: write access for a directory allows deleting of files in the directory even if the user does not have write permissions for the file!)
execute restricts or allows changing into the directory, i.e. cd command
» height=»16″ src=»/moin_static198/light/img/icon_cool.png» title=»Info » width=»16″/> Folders (directories) must have ‘execute’ permissions set (x or 1), or folders (directories) will NOT FUNCTION as folders (directories) and WILL DISAPPEAR from view in the file browser (Nautilus).
Permissions in Action
Using the example above we have the file «/etc/hosts» which is owned by the user root and belongs to the root group.
What are the permissions from the above /etc/hosts ls output?
Changing Permissions
The command to use when modifying permissions is chmod. There are two ways to modify permissions, with numbers or with letters. Using letters is easier to understand for most people. When modifying permissions be careful not to create security problems. Some files are configured to have very restrictive permissions to prevent unauthorized access. For example, the /etc/shadow file (file that stores all local user passwords) does not have permissions for regular users to read or otherwise access.
Источник