Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на 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
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
ТелеграмПодкастБесплатные учебники
Загрузить PDF
Загрузить PDF
В этой статье рассказывается, как перейти в другую папку (каталог) в командной строке Windows. Чтобы работать с командной строкой, необходимо использовать учетную запись администратора.
-
Для этого щелкните по логотипу Windows в нижнем левом углу экрана или нажмите клавишу ⊞ Win на клавиатуре.
- В Windows 8 переместите указатель мыши в верхний правый угол экрана и щелкните по отобразившемуся значку в виде лупы.
-
Значок утилиты командной строки отобразится над строкой поиска.
-
Он имеет вид черного квадрата. Откроется контекстное меню.
-
Эта опции находится в верхней части раскрывшегося меню. Откроется командная строка с правами администратора.
- В открывшемся окне с предложением подтвердить ваши действия нажмите «Да».
- Нельзя запустить командную строку от имени администратора, если вы работаете на компьютере, у которого есть ограничения, который находится в публичном месте или подключен к локальной сети (например, в библиотеке или в школе), то есть в том случае, когда вы пользуетесь гостевой учетной записью.
Реклама
-
После «cd» обязательно добавьте пробел. Эта команда, которая представляет собой сокращение от «change directory» (изменить каталог), является основной командой для перехода в другой каталог.
- Не нажимайте клавишу ↵ Enter.
- Альтернативный вариант — ввести chdir. Эта команда действует точно так же, как «cd».[1]
-
Путь к каталогу — своего рода маршрут, ведущий к определенной папке. Например, если нужным каталогом является папка «System32», которая находится в папке «WINDOWS» на системном диске, путь будет таким: «C:\WINDOWS\System32\».
- Чтобы выяснить путь к папке, перейдите в нее в Проводнике, а затем скопируйте информацию из адресной строки Проводника (сверху).
- Вы можете отобразить список всех каталогов внутри текущего каталога с помощью комадной строки, набрав dir и нажав «Enter».
-
Сделайте это после команды «cd». Убедитесь, что между «cd» и путем к каталогу есть пробел.
- Например, команда может выглядеть так: cd Windows\System32.
- Также можно перетащить папку из Проводника в командную строку.
- По умолчанию местоположением всех папок считается жесткий диск (например, «C:»), поэтому букву жесткого диска вводить не нужно.
-
Так вы перейдете в нужный каталог. Текущий каталог отображается рядом с текстовым курсором (например, «C:\Windows\System32>».)
Реклама
-
и нажмите ↵ Enter, чтобы подняться на один каталог выше. Если вы хотите перейти на один каталог назад (например, из «C:\Windows\System32» в «C:\Windows»), просто наберите «cd..» с двумя точками и нажмите «Enter».
-
Если вы хотите перейти в корневой каталог диска (например, из «C:\Windows\System32» to «C:\»), наберите «cd\» с обратным слешем и нажмите «Enter».
-
Если вы попробуете переместиться в каталог, находящийся на другом диске, с помощью команды «cd», то увидите, что это не сработает. Вам нужно сначала изменить диск. Для этого введите букву, которой обозначен диск, с двоеточией (например, «D:») и нажмите «Enter».
- В качестве альтернативы можете ввести cd /d, а затем полный (включая букву диска) путь к каталогу на другом диске, чтобы непосредственно перейти к нужному каталогу на нем (например, «cd /d D:\Документы».)
-
Введите dir и нажмите ↵ Enter, чтобы отобразить список каталогов внутри текущего. Если вы не уверены, какие каталоги находятся в вашем текущем каталоге, вы можете просмотреть их полный список, набрав «dir» и нажав «Enter».
Реклама
-
Если вы получите сообщение об ошибке «Системе не удается найти указанный путь», проверьте написание имени каталога. Чтобы увидеть список всех каталогов внутри текущего, можете ввести dir и нажать «Enter».
-
Если вы набираете имя верно, но по-прежнему получаете сообщение о той же ошибке, откройте Проводник и проверьте, действительно ли каталог, к которому вы пытаетесь перейти, существует и находится там, где вы думаете.
- Если каталог не существует, вы можете создать новый, введя mkdir, пробел и имя создаваемого каталога. Затем нажмите «Enter».
-
Убедитесь, что каталог расположен на том диске, где вы находитесь в настоящий момент. Команда «cd» не позволяет перейти к каталогу на другом диске. Если ваш текущий диск — это диск C, а каталог, к которому вы хотите переместиться, находится на диске D, вам сначала нужно изменить диск. Для этого введите букву диска и нажмите «Enter».
-
Убедитесь, что вы запустили командную строку от имени администратора. Если командная строка запущена не от имени администратора, набор действий, выполняемых с ее помощью, будет ограничен. Войдите в Windows как администратор, затем щелкните правой кнопкой мыши по значку командной строк в меню «Пуск» и выберите «Запуск от имени администратора».
Реклама
Советы
- Изменить каталог необходимо, чтобы отредактировать или удалить файл.
- Чтобы увидеть полный список команд, выполняемых с помощью командной строки, введите help и нажмите «Enter».
Реклама
Предупреждения
- Попытка запустить из одного каталога команду, связанную с определенным файлом или папкой, находящимися в другом каталоге, приведет к ошибке.
Реклама
Об этой статье
Эту страницу просматривали 833 364 раза.
Была ли эта статья полезной?
Example
One of the most common things you’ll need to do in the command prompt is navigate your file system. To do this, we’ll utilize the cd
and dir
keywords. Start by opening up a command prompt using one of the methods mentioned here. You most likely see something similar to what’s below, where UserName
is your user.
C:\Users\UserName>
Regardless of where in your file structure you are, if your system is like most, we can start with this command:
cd C:\
This will change your current directory to the C:\
drive. Notice how the screen now looks like this
C:\>
Next, run a dir
so we can see anything in the C:\
drive
dir
This will show you a list of files and folders with some information about them, similar to this:
There’s lots of good info here, but for basic navigation, we just care about the right-most column. Notice how we have a Users
folder. That means we can run this
cd Users
Now if you run dir
again, you’ll see all the files and folders in your C:\Users
directory. Now, we didn’t find what we wanted here, so let’s go back to the parent folder. Rather than type the path to it, we can use ..
to go up one folder like so
cd ..
Now we are back in C:\
. If you want to go up multiple folders at once, you can put a backslash and another set of periods like so: cd ..\..
, but we only needed one folder.
Now we want to look in that Program Files
folder. To avoid confusing the system, it’s a good idea to put quotes around the directories, especially when there are spaces in the name. So this time, we’ll use this command
C:\>cd "Program Files"
Now you are in C:\Program Files>
and a dir
command now will tell you anything that’s in here.
So, say we get tired of wandering around to find the folder and looked up exactly where we were needing to go. Turns out it’s C:\Windows\Logs
Rather than do a ..
to Windows
to Logs
, we can just put the full path like so:
cd "C:\Windows\Logs"
And that’s the basics of navigating the command prompt. You can now move through all your folders so you can run your other commands in the proper places.
In this article, let’s learn how to navigate through directories in Command Prompt — The Command Prompt (CMD) in Windows is a powerful tool for executing commands, managing files, and navigating your system. One of the most common tasks you’ll perform in CMD is changing directories, which allows you to move between folders to access and manage files. Whether you’re a beginner or an experienced user, knowing how to change directories in Command Prompt is essential for effective system navigation.
This guide will walk you through the step-by-step process of changing directories in Windows 11 and Windows 10 using basic commands like cd (change directory) and dir (list contents), along with helpful tips to make your file management easier. Whether you’re navigating through your system’s folders, opening a project folder, or accessing a specific directory for troubleshooting, changing directories is a fundamental task in CMD.
Understanding Directories in Windows
When working with Windows, you’ve likely encountered the term «directory.» But what exactly is a directory in Windows? In this article, we’ll delve into the world of directories, exploring their definition, types, and importance in the Windows operating system.
What is a Directory in Windows?
A directory, also known as a folder, is a container used to store and organize files and subdirectories on a computer. It’s a way to categorize and structure your files, making it easier to locate and access them. Think of a directory as a physical file folder, where you can store related documents, images, or other files.
Types of Directories in Windows
- Root Directory: The root directory, denoted by a backslash (), is the topmost directory on a hard drive or storage device. It contains all other directories and files.
- Subdirectories: Subdirectories are directories within directories. They help further organize files and can be nested multiple levels deep.
- System Directories: System directories, such as Windows, System32, and Program Files, are created by the operating system and contain essential files and programs.
- User Directories: User directories, such as Documents, Pictures, Music, and Videos, are created by the operating system for each user account. They serve as default locations for storing personal files.
- Program Directories: Program directories, such as Program Files (x86) and Program Files, contain installed applications and their associated files.
- Temporary Directories: Temporary directories, such as Temp and %temp%, store temporary files created by applications and the operating system.
- System Volume Information: The System Volume Information directory contains system files, such as restore points and indexing data.
- Recycle Bin: The Recycle Bin is a special directory that stores deleted files until they are permanently erased or restored.
- Hidden Directories: Hidden directories, such as AppData and Local Settings, contain configuration files and data used by applications and the operating system. They are hidden by default to prevent accidental modification or deletion.
- Network Directories: Network directories, such as shared folders and network drives, provide access to files and resources on other computers or devices over a network.
- Virtual Directories: Virtual directories, such as those created by subst or mklink commands, are symbolic links that map a directory to a different location on the same or another drive.
- Mount Points: Mount points are directories that serve as entry points for mounted volumes, such as USB drives or network shares.
- Reparse Points: Reparse points are directories that contain reparse data, which allows the operating system to redirect file system requests to a different location.
- Junction Points: Junction points are directories that link to another directory on the same volume, allowing multiple paths to access the same files.
- Symbolic Links: Symbolic links are directories that link to a file or directory on the same or another volume, allowing multiple paths to access the same file or directory.
How to Change Directories in CMD at Different Levels (With Examples)
Before moving ahead with Changing Directories to Windows Folders, we have to understand Directory Changing to Different Levels. Let us discuss all the methods for Changing Directories in CMD at different levels in Windows 10 or 11.
1. Root Level Directory
Open Command Prompt to change to a directory in the root directory (such as»C:\» on Windows), you can use the `cd` command followed by the directory name.
Example:
2. Parent Level Directory
Open Command Prompt to move to a directory within the parent directory (like going from «Documents» to «Users»), simply use the `cd` command followed by `..` to go up one level, and then the name of the parent directory.
Example:
3. Subdirectories Level Directory
Open CMD or Command Prompt to enter a subdirectory within your current directory (such as going from «Documents» to «Photos»), use the `cd` command followed by the name of the subdirectory.
Example:
4. Nested Subdirectories Level
Open CMD to navigate to a deeply nested subdirectory (like going from «Documents» to «Work > Projects»), use the `cd` command with each subdirectory name, separated by a backslash (\).
Example:
5. Leaf Level Directory
Open Command Prompt in Windows 10 or 11 to enter a directory that doesn’t contain any subdirectories (like going to a folder with just files), use the `cd` command followed by the leaf directory’s name.
Example:
Note: Remember, you can always type `cd ..` to go up one level and explore different directories easily.
Changing Directories in Command Prompt to Different Folders
Now, after discussing Directory Change in Different Levels, we will discuss all the possible methods that are required to Change Directories to Folders in the Windows Command Line Tool.
Method 1: Using Drag and Drop
For those who prefer a graphical approach, changing directories using drag and drop is simple. You can open File Explorer, locate the desired directory, and drag it to the Command Prompt window. This action automatically populates the Command Line with the directory path.
Method 2: Using Commands
Changing directories using commands may seem tricky at first, but it’s essential to get the hang of it in Command Prompt. Here are some easy methods to do it:
1. Absolute Paths
This is like using a full address to find a place. In Command Prompt, you can use the full path to a folder to get there directly. This will take you straight to your «Documents» folder. For instance:
2. Relative Paths
Think of this as giving directions from where you are. You can use `..` to move up one level and the folder name to go into a subfolder. This will take you up one level from where you are right now. For example:
3. Drive Letters
Imagine switching between different drives as changing streets. To switch to a different drive, just type its letter and a colon. This will take you to the D: drive. For example:
4. Environment Variables
These are like shortcuts to important places. You can use names like `%USERPROFILE%` to go to common folders without typing the whole path. This will take you to your user profile folder. For example:
5. Tab Auto-Completion
Think of this as your Command Prompt assistant. When you start typing a folder name and press Tab, Command Prompt will try to finish it for you. If there’s more than one option, it will show you a list.
6. Previous Directory (`cd ..`)
This is like having a «go back» button. If you want to return to the folder you were in before, just type `cd ..`. It’s like a quick way to backtrack.
7. Using Wildcards
Wildcards are like search filters. You can use `*` to find folders based on patterns. This will take you to a folder with a name starting with «sep». For example:
cd C:\Users\GFG0338\Desktop\mystuff\my_Sep_Doc>dir sep*.*
8. Using the «dir» command
It lists all Windows Files and Directories (folders) in the current directories. This helps the users to quickly see what Files and Directories are present in a particular location
For example, if you want to list the content of » C:\Users\GFG0338\Desktop\mystuff\my_Doc «, you would type the following:
This will give you a list of Files and Directories in that folder along with respective attributes.
How to Navigate to a Folder in Command Prompt
When you want to navigate to a different folder in the Command Prompt, it’s like giving your computer directions. Here’s how to do it in simple steps:
- Open Command Prompt: First, you need to open Command Prompt in Windows 10 or 11. You can do this by pressing the Windows key, typing «Command Prompt,» and hitting Enter.
- Understand Your Starting Point: Before you start, it’s good to know where you are. Command Prompt opens in a default location, usually your user folder.
- Type ‘cd’ and Space: To tell Command Prompt you want to change the folder, type `cd` (which stands for «change directory») followed by a space.
- Enter the Folder Name: Now, type the name of the folder you want to go to. If your folder name has spaces, put it in double-quotes. For example, if you want to go to a folder named «My Stuff,» you’d type: cd «My Stuff»
- Hit Enter: Press the Enter key on your keyboard. This tells Command Prompt to follow your directions and take you to the folder.
- Check Your Location: To make sure you’re in the right place, you can type `cd` without any folder name and press Enter. Command Prompt will show you the full path of where you are.
Note: Remember, you can always use the `cd ..` command to go up one level if you ever want to backtrack.
Tips for Navigating Directories in Command Prompt
Below we have highlighted a few tips and tricks to make directory navigation in the Command Prompt much easier, let’s check them out:
1. The dir Command
The dir command is being used in CMD to list down all the files and directories in the current folder, here’s a quick example for this:
Example:
dir
2. The cd .. Command
The cd .. command helps in navigating back to the previous directory instantly, here’s a quick example for this:
Example:
cd ..
3. Drag & Drop
You can also choose to simply drag a folder from File Explorer into the Command Prompt. This woll automatically insert the entire path of that directory into CMD.
Tips and Tricks while Changing Directory
There could be five possible reasons if you’re unable to change directory in CMD (command prompt). Let’s identify them in segregated format:
1. Incorrect Syntax
If you are not using the correct command, it might led to throw Syntax error. For example,
cd C:\Path\To\Directory
(no quotes unless the path contains spaces)
2. Permission Issues
Since, normal users have the limited access so there are high chances that you might not beable to access to certain directories. So, it’s recommended to run CMD as an administrator.
3. Non-Existent Directory
Sometimes, we do try to access to a certain directory that might not exist. So, it’s better to verify the path using dir to list down all the available directories.
4. Special Characters or Spaces
If the path contains spaces or special characters, enclose the path in double quotes, For example,
cd "C:\My Folder"
5. Drive Mismatch
If you’re trying to change to a directory on a different drive, make sure to switch drives first by typing the drive letter. For example D:
before using cd
.
D: cd
Best Practices for Directory Management
To ensure efficient directory management, follow these best practices:
- Use Clear and Concise Names: Use descriptive names for directories and files to facilitate easy identification.
- Avoid Deep Nesting: Limit the number of subdirectories within directories to prevent confusion and disorganization.
- Regularly Clean Up Directories: Periodically review and remove unnecessary files and directories to maintain a clutter-free file system.
Conclusion
Changing directories in Command Prompt is an important skill that simplifies file system navigation and task management. Whether you’re working with relative paths, absolute paths, or switching between drives, mastering these commands ensures a smoother and more efficient CMD experience.
Also Read
- Most Useful CMD Commands in Windows
- 10 Ways to Open the Command Prompt in Windows 10
- How to Change Colours in Command Prompt in Windows?
The command prompt or popularly known as cmd in Windows PC comes with a plethora of features and options that one should explore. Starting from how to navigate in cmd to create new files/folder/network test/file transfer. You name it, and there is a shortcut available in cmd to achieve it.
In this article, we will talk in detail about some of the most popular command prompt features, technique and how to navigate in it in more details. Catch us after the jump!
An Overview of Command Prompt:
Microsoft introduced cmd since they launched their first OS called MS-DOS.
From that day till now, Microsoft has added more features, and updated old cmd commands those were not supported.
As working from cmd gives more programmer like feeling and is used mostly by tech guy. Thus, they love working on from Terminal, especially those who are a fan of Mac or Linux OS.
Now let’s talk about some of the most popular command prompt commands that you can use on a day-to-day basis:
- cmd – launch command quick window
- cd – current directory
- mkdir – make a directory or folder
- chdir – displays the current directory
- cls – clears the content from screen
- ver – displays the current version of cmd prompt
- exit – close the command prompt window
- ping – check the status of network packets
- scan disk – run and scans disk health from a command prompt
- type – displays what is inside of a file
- debug – starts to debug feature within cmd prompt
- edit – used to edit files from cmd prompt
This is an exciting part where we will discuss how to use the commands mentioned above and navigate in command prompt.
Let’s start with the basic command prompt by launching a command prompt from Windows start by typing in the search box as “cmd.”
Cmd is used to launch command prompt window on Windows-based PC. It can be Window XP/Vista/7/8/10.
In the open command prompt window, it will display the current version of cmd along with the current directory we are.
By default, it will open as C:\Users\ [Username] and a blinking cursor waiting for commands to execute.
cd
cd
As we know, cd stands for the current directory, and it displays the current working directory in which you are working.
To change the directory and access a file, you can type as below:
cd ..
(to move out of current directory)
and to move into a directory enter:
cd foldername
mkdir
mkdir
mkdir stands for make directory or folder in Windows. This command helps to create a new folder name on the location where you want.
For example, when we launched the command prompt, it opened in default location as Desktop, but I wanted to create a sysprobs folder in my pictures folder to save important images.
Thus, I did cd… to move out of Desktop and move into pictures folder, and then I created a folder sysprobs.
Advance user can also create a folder at any location without moving out of the current directory by just inserting the valid path of the place where they want to make the file or folder.
dir
dir is a useful command to view the files and folders inside the particular folder. Once you verified that you are in the correct location, enter:
dir
If the folder contains lots of files and folders, then you can use below commands to filter the results.
- List the files/folders name starting with particular letters:
dir ubuntu*
- Display the file/folder name ending with certain letters.
dir *ubuntu
- This command will display the files and folders name contain particular letters.
dir *linux*
- To navigate from one location to another drive, you can simply type the drive letter with :, as shown below.
We mentioned some of the useful commands to navigate disks, folders and files in CMD. As you must aware, you can find the useful switches with every command by typing the /? as shown below.
dir /?
copy con filename.txt
To create a text file in the folder we just created, you can try below command:
copy con filename.txt
then enter key. Once above command is executed it will provide you with blank space on command prompt to enter any information that you want to add into the file.
For example, I tried “I love sysprobs”, and press enter. And it will be saved to the file we created above.
To get out of the command line interface press CTRL+Z to break the chain.
Here is the text file created from command prompt with the content we entered.
chdir
Chdir displays the current working directory, the location in which you are currently working.
In other words, any information created or saved will be in that particular location.
To access the current working directory, a user can try typing chdir, and it will display the location of the current directory.
chdir
Cls
Cls command stands for clear. To remove any typed information from the command prompt screen, user can type in cls, and it will clear the complete cmd screen.
cls
Ver
Ver stands for version, and it is used to display the current version of Windows command prompt utility.
As Microsoft keeps adding new useful commands and updates old one with more features hence having an idea of the current build of command is a good have to feature.
The version of command can be located using Ver and enter, as shown below:
ver
Exit:
Exit command helps to close the command prompt.
When you want to close the cmd screen and move out, you can type exit and enter. The command will close the Window.
exit
Other Useful Commands
Ping
Ping is a handy command that tells you the information related to network connectivity.
The ping command is used to check the status of network connectivity based on send and received packets of data.
For example: If I want to check my internet connectivity, then I will use the ping command to check whether I can access the WorldWideWeb.
Let’s get to a practical example to understand in detail:
To check network connectivity, I need to either enter an IP address that I am trying to access or FQDN address like google.com/bing.com etc.
For convenience, I will use google.com for my ping test.
Ping google.com
The ping process will start and will run for some time and will automatically show you the summary report of the ping, as shown below:
Scan disk
Scan disk (chkdsk) is another impressive command-line utility that scans and repair any issue related to hard disk.
It can be accessed by running a command prompt with admin rights.
User can try below command to run scan disk:
chkdsk
Conclusion:
Just like commands we have shared above, there are many such available that a user can use as per their conveniences like debug/type/scan disk and many more.
Do let us know which is your favourite command prompt command that you frequently use in the comment section below.