Как создать каталог в cmd windows

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

Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на 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

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

ТелеграмПодкастБесплатные учебники

To create a directory using cmd, you can use the `mkdir` command followed by the desired directory name.

mkdir NewFolder

Understanding Directories

What is a Directory?

A directory is essentially a collection of files and other directories that helps organize your computer’s data. In many graphical user interfaces, these are represented as folders. Directories serve as a crucial organizational tool, allowing users to easily locate and manage their files.

Why Use Cmd for Directory Creation?

Using the Command Prompt (cmd) for directory creation offers several advantages:

  • Speed and Efficiency: Quickly create directories without navigating through multiple windows.
  • Powerful Automation: Easily integrate directory creation into batch scripts, optimizing repetitive tasks.
  • Advanced Control: Manage multiple directories at once or create nested structures effortlessly.

How to Change Directory Drive in Cmd: A Quick Guide

How to Change Directory Drive in Cmd: A Quick Guide

Basic Command Syntax

To create a directory using cmd, you utilize the `mkdir` command. The basic syntax for this command is:

mkdir [directory_name]

This simple command creates a new directory with the specified name in the current working directory.

Creating a Simple Directory

Creating a new directory is straightforward. For instance, you can create a directory named `MyNewFolder` by executing the following command:

mkdir MyNewFolder

When you run this command, cmd will create a new folder named «MyNewFolder» in your current directory, ready for you to add files or subdirectories.

How to Make Folder Using Cmd in a Snap

How to Make Folder Using Cmd in a Snap

How to Create Nested Directories

Understanding Nested Directories

Nested directories are directories created within another directory. This structure is essential for better organization of your files, especially when dealing with complex projects or large volumes of data.

Using the `mkdir` Command for Nested Directories

To create a nested directory structure, use the `mkdir` command with a specified path. For example, to create a parent directory named `ParentFolder` and a child directory called `ChildFolder`, use the command:

mkdir ParentFolder\ChildFolder

In this example, `ChildFolder` is created within `ParentFolder`. By creating multiple nested directories in a single command, you can improve efficiency further:

mkdir ParentFolder\ChildFolder1 ParentFolder\ChildFolder2

This command creates both `ChildFolder1` and `ChildFolder2` within `ParentFolder` at once.

How to Delete Folders Using Cmd: A Step-by-Step Guide

How to Delete Folders Using Cmd: A Step-by-Step Guide

How to Create a Directory with Spaces in Name

Using Quotes for Directory Names

When creating directories with spaces in their names, be sure to encapsulate the name in quotes. This ensures that cmd interprets the entire phrase as a single directory name. For instance:

mkdir "My New Folder"

This command successfully creates a directory named «My New Folder,» allowing you to maintain clarity in naming.

Navigate to Directory in Cmd: A Simple Guide

Navigate to Directory in Cmd: A Simple Guide

How to Make a Directory in a Specific Location

Specifying Path in Command

You can create directories in specific locations by providing the full path in the command. This practice is particularly useful when you want to organize directories in different sections of your file system.

Example for Creating a Directory in a Specific Location

To create a directory named `NewFolder` inside your `Documents` folder, execute:

mkdir C:\Users\YourUserName\Documents\NewFolder

This command directs cmd to create the new directory exactly where specified, based on the path provided.

Force Delete Directory in Cmd: A Simple Guide

Force Delete Directory in Cmd: A Simple Guide

How to Make Directory in Windows CMD: Advanced Techniques

Creating Multiple Directories at Once

When working with projects requiring multiple directories, you can create them simultaneously. For instance, to create three project directories under a «Projects» directory, use:

mkdir Projects\2023\{Project1, Project2, Project3}

This command allows for efficient organization, as it creates individual project directories with minimal effort.

Using the `md` Command

The `md` command functions as an alias for `mkdir`. Thus, you can use either interchangeably:

md AnotherNewFolder

This command performs identically to `mkdir`, creating a new directory called `AnotherNewFolder`.

Deleting Directory in Cmd: A Simple Guide

Deleting Directory in Cmd: A Simple Guide

Error Handling in CMD

Common Errors While Creating Directories

While creating directories in cmd, you may encounter several common errors. Here are a few:

  • Directory Already Exists: If you try to create a directory that already exists, cmd will display an error message. To avoid this, check if the directory is already there by using the `dir` command.
  • Incorrect Path: Providing an incorrect path will also generate an error. Always verify the path to ensure it exists prior to using it in your command.

Tips on What to Check and How to Correct

When experiencing errors, check for:

  • Typographical errors in directory names or paths.
  • The current working directory if you’re creating a directory without specifying the full path.
  • Permissions issues, especially if working in protected system folders.

Show Directory Cmd: A Quick Guide to Viewing Directories

Show Directory Cmd: A Quick Guide to Viewing Directories

Verifying Directory Creation

How to Check Created Directories

After executing your commands to create directories, you can verify their existence using the `dir` command:

dir MyNewFolder

This command lists the contents of `MyNewFolder`, confirming its successful creation. You can also check all directories in your current location by simply typing:

dir

This command will display all files and folders, allowing you to ensure your new directories are in place.

Mastering Open Directory Cmd in Quick Steps

Mastering Open Directory Cmd in Quick Steps

Conclusion

Creating directories using cmd is a valuable skill that enhances your ability to manage and organize files efficiently on your system. By understanding basic commands, working with nested structures, and employing advanced techniques, you can optimize your workflow significantly. Embrace these cmd commands and incorporate them into your daily routines for seamless directory management.

How to Create Folder Through Cmd Efficiently

How to Create Folder Through Cmd Efficiently

Additional Resources

For those looking to deepen their understanding, consider exploring further resources on cmd commands. Tutorials and videos can also provide visual guidance on mastering this powerful tool.

Download File Using Cmd: A Simple How-To Guide

Download File Using Cmd: A Simple How-To Guide

Call to Action

We invite you to share your experiences or any questions you may have about creating directories using cmd in the comments section below. Join us on this journey to explore more cmd commands and enhance your skills today!

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Настройка sccm windows server 2019
  • Resolve dns name windows
  • Разделить зеркальный том windows 10
  • Где найти папку hosts windows 10
  • Intel sensor driver hp windows 10