- Как создавать каталоги в 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 create a directory or folder
- Creating a folder in Microsoft Windows
- My Computer or Windows Explorer
- Windows desktop
- Create a new folder using a shortcut key
- Windows command line
- Creating a directory in MS-DOS and the Windows command line
- Related pages
- Create a directory with a batch file
- Creating a directory in Linux, Unix, and their variants
- Creating a folder and directory in Microsoft Windows 3.X
- File Manager
- MS-DOS
- Creating a folder in macOS X
- Desktop folder
- Create a folder in a directory
- How to Create Directory in Linux using mkdir Command
- 1) mkdir command
- 2) Create multiple directories
- 3) Add directory include its sub-directory
- 4) Set access privilege
- 5) Print message for each created directory
- 6) Create Directory with Date
- Conclusion
Как создавать каталоги в 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 create a directory or folder
There are multiple ways to create or add a folder, subfolder, directory, and subdirectory on a computer. The methods depend on the operating system or where the directory is being created. Select a link below for steps on how to create a directory and folder in each major operating system.
Creating a folder in Microsoft Windows
My Computer or Windows Explorer
- Open My Computer or Windows Explorer.
- Open the drive or folder where you’d like to create the new folder; for example, the C: drive. If you do not want to create a folder in the root directory, browse to the location of your choosing.
- In Windows 10 on the Home tab, click the New folder icon. In Windows 7 and earlier on the file menu bar, select File and then Folder.
In all versions of Windows, you can also right-click with your mouse on a blank portion of the folder, select New and then Folder.
If you’re using Windows 7 or earlier and do not see the file menu bar at the top of Windows Explorer, press the Alt key and it should become visible.
Windows desktop
- Navigate to the Windows desktop.
- Right-click any blank portion of the desktop.
- In the menu that appears (like that shown in the picture), click New and then Folder.
- A new folder appears. Type the name of the folder you want to use and then press Enter .
Create a new folder using a shortcut key
While in Windows Explorer, you can press Ctrl + Shift + N to create a new folder without using the mouse.
Windows command line
See the following MS-DOS and Windows command line user section for information about creating a directory in the Windows command line.
Creating a directory in MS-DOS and the Windows command line
It is more appropriate to use «directory» instead of «folder» when referring to the command line.
To create a directory in MS-DOS or the Windows command line (cmd), use the md or mkdir MS-DOS command. For example, below we are creating a new directory called «hope» in the current directory.
You can also create multiple new directories in the current directory with the md command. In the next example, we are creating three new directories, called «user1,» «user2,» and «user3,» in the current directory.
If you want to create a directory with spaces, you need to surround the directory name with quotes. In the example below, we are creating a directory called «my example directory» in the current directory.
To create a directory in the parent directory, without first moving into that directory, you can use the command below. This example moves back one directory to create the «example» directory.
To create a subdirectory in a different directory without moving it, use a command similar to the example below. This command creates a «test» directory in the hope directory.
Once a directory is created, you can use the cd command to change the directory and move into that directory.
To make a directory in another drive without moving into that drive, use a command similar to the example below. This command creates an «example» directory on the F: drive. The drive letter «f:» can be substituted from any drive letter.
Related pages
Create a directory with a batch file
A batch file is a series of commands that can be entered in the command line. Therefore, you can use any of the examples from the section above in the batch file to create a new folder.
Creating a directory in Linux, Unix, and their variants
It is more appropriate to use «directory» instead of «folder» when in a command line.
You must have the permissions to create a directory outside of your home directory.
To create a directory in Linux, Unix, or any variant, use the mkdir Linux and Unix command. For example, below we are creating a new directory called hope in the current directory.
Once the directory is created, you can use the cd command to change the directory and move into that directory.
If you want to change the permissions of a directory after its been created, use the chmod command.
Creating a folder and directory in Microsoft Windows 3.X
File Manager
- Open File Manager
- Open the folder where you’d like to place the new folder and on the top menu of File Manager, select File and then new folder.
MS-DOS
See the above MS-DOS user section for information about creating a directory in MS-DOS.
Creating a folder in macOS X
Desktop folder
- Navigate to the macOS desktop.
- Right-click (tap two fingers on the mouse) any blank space on the desktop.
- Select New Folder from the drop-down menu that appears.
- Name the folder, and then press Return .
Create a folder in a directory
- Open Finder and navigate to the directory where you’d like to create the folder.
- Click File in the upper-left corner of the screen.
- Select New Folder in the drop-down menu that appears.
- Name the folder, and then press Return .
Users may also press the shortcut key combination Command + Shift + N to create a new folder.
To create a directory in the Terminal command line, see the Linux steps.
Источник
How to Create Directory in Linux using mkdir Command
Let’s check how to create a directory in the Linux system. On Linux, we can use ‘mkdir’ command. Mkdir is short for “make directory”. All most all Linux distribution like Ubuntu, RHEL, Debian and Centos uses the same command.
In this tutorial, I will show you 5 usage mkdir command to create directory on a Linux and Unix like operating system.
1) mkdir command
You can type mkdir directly from your console to use it.
By default, running mkdir without any parameter will create a directory under the current directory. Here’s a sample of it:
From the screenshot above, we created a directory called ‘office’. When we run mkdir command, we are in ‘/home/pungki’ directory. So then the new directory, which is office, is created under /home/pungki directory. If we put an exact location — for example : ‘/usr/local’ — , then Linux will create a directory under ‘/usr/local’ directory.
When Linux found that the directory which suppose to be created already exists, then the tool will tell us that it can’t create it.
Another pre-requisite for creating a directory that you must have access to the location where the directory wants to be created. When you don’t have it then mkdir will report an error.
2) Create multiple directories
We can also create multiple directories at the same time. Let say we want to create directories named ‘ubuntu’, ‘redhat’ and ‘slackware’. Then the syntax will be like this :
3) Add directory include its sub-directory
When you want to create sub-directories , you will need to use -p parameter. This parameter will create parent directory first, if mkdir cannot find it. Let say we want to create directory named ‘letter’ and directory named ‘important’ under directory letter. Then the syntax will be like this:
4) Set access privilege
Using -m parameter, we can also set the access privilege for the new directory on-the-fly. Here’s an example.
The above command will create a directory named letter and give access privilege read-only for the directory owner, directory group owner and anybody.
5) Print message for each created directory
The -v option will print message on console for each created directory. Check the following example.
6) Create Directory with Date
Do you know that you can create a directory name with date? This is mostly useful in shell scripts when you require to create backup folders with date.
Conclusion
Mkdir command is one of the basic commands used in in Linux. As usual, you can always type man mkdir or mkdir —help to display manual page and explore it more detail.
Источник