From Wikipedia, the free encyclopedia
The |
|
Developer(s) | Various open-source and commercial developers |
---|---|
Written in | python3 |
Operating system | Unix, Unix-like, Plan 9, Inferno, DOS, MSX-DOS, FlexOS, OS/2, Windows, ReactOS, KolibriOS |
Platform | Cross-platform |
Type | Command |
License | GNU coreutils: GPLv3+ MS-DOS, Plan 9: MIT FreeDOS: GPLv2+ ReactOS: GPLv2 |
The mkdir
(make directory) command in the Unix, DOS, DR FlexOS,[1] IBM OS/2,[2] Microsoft Windows, and ReactOS[3] operating systems is used to make a new directory. It is also available in the EFI shell[4] and in the PHP scripting language. In DOS, OS/2, Windows and ReactOS, the command is often abbreviated to md
.
The command is analogous to the Stratus OpenVOS create_dir
command.[5] MetaComCo TRIPOS and AmigaDOS provide a similar MakeDir
command to create new directories.[6][7] The numerical computing environments MATLAB and GNU Octave include an mkdir
function with similar functionality.[8][9]
In early versions of Unix (4.1BSD and early versions of System V), this command had to be setuid root as the kernel did not have an mkdir
syscall. Instead, it made the directory with mknod
and linked in the .
and ..
directory entries manually. The command is available in MS-DOS versions 2 and later.[10] Digital Research DR DOS 6.0[11] and Datalight ROM-DOS[12] also include an implementation of the md
and mkdir
commands.
The version of mkdir
bundled in GNU coreutils was written by David MacKenzie.[13]
It is also available in the open source MS-DOS emulator DOSBox and in KolibriOS.[14]
mkdir
commandNormal usage is as straightforward as follows:
where name_of_directory
is the name of the directory one wants to create. When typed as above (i.e. normal usage), the new directory would be created within the current directory. On Unix and Windows (with Command extensions enabled,[15] the default[16]), multiple directories can be specified, and mkdir
will try to create all of them.
On Unix-like operating systems, mkdir
takes options. The options are:
-p (--parents)
: parents or path, will also create all directories leading up to the given directory that do not exist already. For example,mkdir -p a/b
will create directorya
if it doesn’t exist, then will create directoryb
inside directorya
. If the given directory already exists, ignore the error.-m (--mode)
: mode, specify the octal permissions of directories created bymkdir
.
-p
is most often used when using mkdir
to build up complex directory hierarchies, in case a necessary directory is missing or already there. -m
is commonly used to lock down temporary directories used by shell scripts.
An example of -p
in action is:
If /tmp/a
exists but /tmp/a/b
does not, mkdir
will create /tmp/a/b
before creating /tmp/a/b/c
.
And an even more powerful command, creating a full tree at once (this however is a Shell extension, nothing mkdir does itself):
mkdir -p tmpdir/{trunk/sources/{includes,docs},branches,tags}
If one is using variables with mkdir in a bash script, POSIX `special’ built-in command ‘eval’ would serve its purpose.
DOMAIN_NAME=includes,docs eval "mkdir -p tmpdir/{trunk/sources/{${DOMAIN_NAME}},branches,tags}"
This will create:
tmpdir ________|______ | | | branches tags trunk | sources ____|_____ | | includes docs
- Filesystem Hierarchy Standard
- GNU Core Utilities
- Find – The find command coupled with mkdir can be used to only recreate a directory structure (without files).
- List of Unix commands
- List of DOS commands
- ^ «Users guide» (PDF). bitsavers.org. Archived from the original (PDF) on 2019-09-25. Retrieved 2019-10-22.
- ^ «JaTomes Help — OS/2 Commands». www.jatomes.com.
- ^ «GitHub — reactos/reactos: A free Windows-compatible Operating System». October 22, 2019 – via GitHub.
- ^ «EFI Shells and Scripting». Intel. Retrieved 2013-09-25.
- ^ «Reference manual» (PDF). stratadoc.stratus.com. Retrieved 2019-10-22.
- ^ «Introduction to Tripos» (PDF). Retrieved 2019-10-22.
- ^ Rügheimer, Hannes; Spanik, Christian (October 22, 1988). AmigaDOS quick reference. Grand Rapids, Mi : Abacus. ISBN 9781557550491 – via Internet Archive.
- ^ «Make new folder — MATLAB mkdir». www.mathworks.com.
- ^ «Function Reference: mkdir». octave.sourceforge.io.
- ^ Wolverton, Van (2003). Running MS-DOS Version 6.22 (20th Anniversary Edition), 6th Revised edition. Microsoft Press. ISBN 0-7356-1812-7.
- ^ «DR DOS 6.0 User Guide Optimisation and Configuration Tips» (PDF). Archived from the original (PDF) on 2019-09-30. Retrieved 2019-08-13.
- ^ «Datalight ROM-DOS User’s Guide» (PDF). www.datalight.com.
- ^ «mkdir(1): make directories — Linux man page». linux.die.net.
- ^ «Shell — KolibriOS wiki». wiki.kolibrios.org.
- ^ «Microsoft Windows XP — Mkdir». Microsoft. Archived from the original on July 22, 2016. Retrieved 25 October 2012.
- ^ «Microsoft Windows XP — Cmd». Microsoft. Retrieved 25 October 2012.
- Cooper, Jim (2001). Special Edition Using MS-DOS 6.22, Third Edition. Que Publishing. ISBN 978-0789725738.
- Kathy Ivens; Brian Proffit (1993). OS/2 Inside & Out. Osborne McGraw-Hill. ISBN 978-0078818714.
- Frisch, Æleen (2001). Windows 2000 Commands Pocket Reference. O’Reilly. ISBN 978-0-596-00148-3.
- Barrett, Daniel J. (2012). Macintosh Terminal Pocket Guide: Take Command of Your Mac. O’Reilly. ISBN 978-1449328986.
- Microsoft TechNet Mkdir article
mkdir
: make directories – Shell and Utilities Reference, The Single UNIX Specification, Version 5 from The Open Groupmkdir(1)
– Plan 9 Programmer’s Manual, Volume 1mkdir(1)
– Inferno General commands Manual
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
In Windows, we can create directories from command line using the command mkdir(or md). Syntax of this command is explained below.
Create a folder from command line:
mkdir foldername
For example, to create a folder named ‘newfolder‘ the command is:
mkdir newfolder
Create directory hierarchy
We can create multiple directories hierarchy(creating folder and sub folders with a single command) using mkdir command.
For example, the below command would create a new folder called ‘folder1’ and a sub folder ‘folder2’ and a sub sub folder ‘folder3’.
mkdir folder1\folder2\folder3.
The above command is same as running the below sequence of commands.
mkdir folder1 mkdir folder1\folder2 mkdir folder1\folder2\folder3
Permissions issue
Yoou need to have permissions to create folder for the command to work. Not having permissions to create folder would throw up ‘access denied’ error.
C:\Users>mkdir c:\Windows\System32\test Access is denied.
If there exists a file or folder with the same name, the command throws up error.
C:\>md test A subdirectory or file test already exists.
If you don’t see a file or folder with that name, make sure to check if it’s not hidden.
Handling whitespaces
If the name needs to have space within, you should enclose it in double quotes.
For example, to create a folder with the name ‘My data’, the command would be
c:\>mkdir "my data"
Creating multiple folders
mkdir command can handle creating multiple folders in one go. So you can specify all the folders you wanted to create like below
C:\>mkdir folder1 folder2 subfolder1/folder3 subfolder2/subfolder21/folder4
The syntax of the command is incorrect.
If you get this error, make sure you are using the directory paths in Windows format and not in Linux format. On Linux, the directory paths are separated with ‘/’, but in Windows it’s ‘\’.
c:\>mkdir folder1/folder2 The syntax of the command is incorrect.
The right command is
c:\>mkdir folder1\folder2
The `mkdir` command in CMD is used to create a new directory (folder) in the specified location.
mkdir C:\ExampleFolder
Understanding the `mkdir` Command
The `mkdir` command stands as a fundamental tool in the command-line interface, specifically for creating new directories within the Windows operating system. The syntax for the `mkdir` command is simple yet powerful, allowing users to create directories quickly.
Mastering Cmd Directory Navigation Made Simple
Basic Usage of `mkdir`
Creating a Single Directory
To create a single directory, the command is straightforward. Here’s how it works:
mkdir NewFolder
This command tells the system to create a new directory named NewFolder in the current working directory. Once executed, users can confirm the creation by using the `dir` command, which lists all directories and files in the current location.
Creating Multiple Directories at Once
One of the strengths of `mkdir` is its ability to create multiple directories simultaneously. For example, if you want to create three new folders in one command, you can use:
mkdir Folder1 Folder2 Folder3
This command effectively creates Folder1, Folder2, and Folder3 at once, streamlining the organizational process.
Mastering Cmd Rmdir: Effortless Directory Removal Guide
Advanced Options of `mkdir`
Creating Nested Directories
Nested directories are a practical way to keep related files organized. If you wish to create directories within each other, the syntax is:
mkdir Parent\Child\Grandchild
This command will create a hierarchy where Parent contains Child, and Child contains Grandchild. This is exceptionally useful for projects with a structured format.
Using the `/p` Parameter
The `/p` parameter allows users to create nested directories even if some parent directories do not yet exist. Here’s how it works:
mkdir Parent\Child\Grandchild /p
This command will create the entire path, including Parent, Child, and Grandchild, regardless of whether the parent directories already exist. It ensures that you can create a complete structure in one go, reducing the need for multiple commands.
Mastering Cmd Dir List for Quick Directory Insights
Error Handling with `mkdir`
Common Errors and Solutions
While using `mkdir`, users may encounter common errors. Understanding these can save time and frustration.
For instance, if you try to create a directory in a non-existent path, you might see the error:
The system cannot find the path specified.
To resolve this, double-check the path before executing the command. Ensure that each parent directory in the intended path exists unless you are using the `/p` option.
Mastering Cmd Md: A Quick Guide to Cmd Mastery
Best Practices for Using `mkdir`
Naming Conventions
When creating directories, clear and descriptive names aid in navigation and organization. Avoid using spaces and special characters to ensure compatibility across different systems and software. For instance, prefer ProjectFiles over Project Files.
Organizing Directories
Effective organization is essential for productivity. Before creating directories, take a moment to plan the structure. Consider how files will be used, and create top-level directories that make logical sense for your projects.
Mastering Cmd Disklist: Your Quick Guide to Disk Management
Examples of Practical Uses
Structuring a Project Directory
Let’s say you have a new project and need to organize your files efficiently. You might run the following command:
mkdir Project\Source Project\Docs Project\Assets
This way, you create a logical structure where Source, Docs, and Assets fall under the Project directory. Each directory can serve a unique purpose, simplifying file retrieval and management.
Creating Directories for Scripting
For those interested in automation, using `mkdir` in batch files can significantly speed up the setup of a workspace. For example, a simple batch script might look like this:
@echo off
mkdir Project\{Source,Docs,Assets}
This enables the rapid creation of a project structure every time you need to start a new project, illustrating the power of integrating `mkdir` with scripting.
Mastering Cmd DISM: Your Quick Guide to Deployment
Conclusion
The `mkdir` command is a versatile and essential tool in the command line arsenal for any Windows user. By mastering this command, you can streamline your directory creation process, enhance your organizational skills, and ultimately become more efficient in your workflows. With practice, you’ll find the countless opportunities to implement `mkdir` into your daily tasks. For those eager to expand their command line knowledge, delving deeper into CMD commands will open up a wider world of efficiency and control.
Mastering Cmd Kill: A Quick Guide to Terminating Processes
Additional Resources
For further learning, consider exploring resources on CMD commands, scripting tutorials, and best practices for directory management. Continual learning will enhance your command line proficiency and boost your productivity in dealing with technology.
Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на Github или отредактировать документ в vim. Всё это происходит так часто, что все основные действия с файлами становится быстрее и привычнее выполнять в консоли. Рассказываем и показываем основные команды, которые помогут ускорить работу в терминале под OS Windows.
Для начала нужно установить терминал или запустить командную строку, встроенную в Windows — для этого нажмите Win+R
и введите cmd
. Терминал часто встречается и прямо в редакторах кода, например, в Visual Studio Code.
Чтобы ввести команду в консоль, нужно напечатать её и нажать клавишу Enter
.
Содержимое текущей папки — dir
Выводит список файлов и папок в текущей папке.
C:\content-server>dir
Том в устройстве C имеет метку SYSTEM
Серийный номер тома: 2C89-ED9D
Содержимое папки C:\content-server
06.10.2020 00:41 <DIR> .
06.10.2020 00:37 <DIR> .circleci
16.07.2020 16:04 268 .editorconfig
16.07.2020 16:04 10 .eslintignore
16.07.2020 16:04 482 .eslintrc
06.10.2020 00:37 <DIR> .github
16.07.2020 16:04 77 .gitignore
06.10.2020 00:41 <DIR> assets
06.10.2020 00:41 <DIR> gulp
16.07.2020 16:10 379 gulpfile.js
16.07.2020 16:10 296 320 package-lock.json
16.07.2020 16:10 751 package.json
16.07.2020 16:04 509 README.md
Открыть файл
Чтобы открыть файл в текущей папке, введите его полное имя с расширением. Например, blog.txt или setup.exe.
Перейти в другую папку — cd
Команда cd
без аргументов выводит название текущей папки.
Перейти в папку внутри текущего каталога:
C:\content-server>cd assets
C:\content-server\assets>
Перейти на одну папку вверх:
C:\content-server\assets>cd ..
C:\content-server>
Перейти в папку на другом диске:
c:\content-server>cd /d d:/
d:\>
Чтобы просто изменить диск, введите c:
или d:
.
Создать папку — mkdir или md
Создаём пустую папку code
внутри папки html
:
d:\html>mkdir coded:\html>dir
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:25 <DIR> code
0 файлов 0 байт
3 папок 253 389 438 976 байт свободно
Создаём несколько пустых вложенных папок — для этого записываем их через косую черту:
d:\html>mkdir css\js
d:\html>dir
Том в устройстве D имеет метку DATA
Серийный номер тома: 0000-0000
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:25 <DIR> code
03.11.2020 19:29 <DIR> css
Создаётся папка css
, внутри которой находится папка js
. Чтобы проверить это, используем команду tree
. Она показывает дерево папок.
Удалить папку — rmdir или rd
Чтобы удалить конкретную папку в текущей, введите команду rmdir
:
d:\html\css>rmdir js
При этом удалить можно только пустую папку. Если попытаться удалить папку, в которой что-то есть, увидим ошибку:
d:\html\css>d:\html>rmdir css
Папка не пуста.
Чтобы удалить дерево папок, используйте ключ /s
. Тогда командная строка запросит подтверждение перед тем, как удалить всё.
d:\html>rmdir css /s
css, вы уверены [Y(да)/N(нет)]? y
Показать дерево папок — tree
В любом момент мы можем увидеть структуру папок. Для этого используется команда tree
.
d:\html>tree
Структура папок тома DATA
Серийный номер тома: 0000-0000
D:.
├───code
└───css
└───js
Если вы хотите посмотреть содержимое всего диска, введите tree
в корне нужного диска. Получится красивая анимация, а если файлов много, то ещё и немного медитативная.
Удаление файла — del или erase
Команда для удаления одного или нескольких файлов.
d:\html>del blog.txt
Переименование файла — ren или rename
Последовательно вводим ren
, старое и новое имя файла.
d:\html>dir
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:59 0 blag.txt
d:\html>ren blag.txt blog.txt
d:\html>dir
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:59 0 blog.txt
Команды одной строкой
Очистить консоль — cls
.
Информация о системе — systeminfo
.
d:\html>systeminfo
Имя узла: DESKTOP-6MHURG5
Название ОС: Майкрософт Windows 10 Pro
Версия ОС: 10.0.20246 Н/Д построение 20246
Изготовитель ОС: Microsoft Corporation
Параметры ОС: Изолированная рабочая станция
Сборка ОС: Multiprocessor Free
Информация о сетевых настройках — ipconfig
.
d:\html>ipconfig
Настройка протокола IP для Windows
Адаптер Ethernet Ethernet 2:
Состояние среды. . . . . . . . : Среда передачи недоступна.
DNS-суффикс подключения . . . . . :
Список запущенных процессов — tasklist
.
c:\>tasklist
Имя образа PID Имя сессии № сеанса Память
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 8 КБ
System 4 Services 0 2 688 КБ
Secure System 72 Services 0 23 332 КБ
…
Справка по командам — help
Команда help
без аргументов выводит список всех возможных команд. help
вместе с именем команды выведет справку по этой команде.
d:\html>help tree
Графическое представление структуры папок или пути.
TREE [диск:][путь] [/F] [/A]
/F Вывод имён файлов в каждой папке.
/A Использовать символы ASCII вместо символов национальных алфавитов.
В этой статье приведены не все команды и не все их возможности, но вы всегда можете воспользоваться командой help
и узнать о том, что ещё может командная строка.
👉🏻 Больше статей о фронтенде и работе в айти в телеграм-канале.
Подписаться
Материалы по теме
- 10 горячих клавиш VS Code, которые ускорят вашу работу
- Полезные команды для работы с Git
- Полезные команды для работы с Node. js
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
ТелеграмПодкастБесплатные учебники