Командная строка Windows — это один из самых мощных инструментов на ПК. С ее помощью можно напрямую взаимодействовать с операционной системой и выполнять различные действия, которые недоступны в графическом интерфейсе (GUI).
В этой статье мы покажем вам 40 операций, которые можно использовать в командной строке Windows. Они помогут вам стать более уверенным пользователем.
Операции в командной строке Windows
powershell start cmd -v runAs – запускает командную строку от имени администратора. Ввод этой команды откроет новое окно командной строки с правами администратора.
driverquery – отображает все установленные драйвера. Важно иметь доступ ко всем драйверам, так как они часто вызывают проблемы. Эта команда показывает даже те драйверы, которые не отображаются в диспетчере устройств.
chdir или cd – меняет текущий рабочий каталог на указанный каталог.
systeminfo – показывает информацию о вашем ПК. Эта команда предоставляет подробную информацию о системе, которую нельзя увидеть в графическом интерфейсе.
set – показывает переменные среды вашего компьютера.
prompt – меняет текст, отображаемый перед вводом команд. По умолчанию командная строка показывает путь к диску C. Вы можете изменить этот текст с помощью команды prompt с синтаксисом: prompt имя_подсказки $G.
Примечание: если не добавить $G к команде, символ «>» не появится перед текстом.
clip – копирует элементы в буфер обмена. Например, dir | clip копирует содержимое текущего каталога в буфер обмена. Можно ввести clip /? и нажать ENTER для получения инструкций.
assoc – отображает программы и связанные с ними расширения файлов.
title – меняет заголовок окна командной строки с помощью команды: title имя_заголовка
fc – сравнивает два файла. Эта команда полезна для быстрого выявления различий между двумя файлами. Пример: fc «путь_к_файлу1» «путь_к_файлу2».
cipher – очищает диск и шифрует данные. Удаленные файлы остаются доступными.
netstat -an – показывает открытые порты, их IP-адреса и состояния.
ping – вычисляет IP-адреса сайта и время передачи данных.
color – меняет цвет текста командной строки.
Ввод команды color 2 покажет доступные цвета.
for /f «skip=9 tokens=1,2 delims=:» %i in (‘netsh wlan show profiles’) do @echo %j | findstr -i -v echo | netsh wlan show profiles %j key=clear – показывает все пароли Wi-Fi.
ipconfig – выдает информацию об IP-адресах и сетевых подключениях. Команда имеет расширения, например: ipconfig /release, ipconfig /renew, ipconfig /flushdns для устранения проблем с интернет-соединением.
sfc – проверяет системные файлы. Команда сканирует и исправляет поврежденные файлы. Используйте расширение /scannow для запуска проверки.
powercfg – меняет настройки питания. Команда имеет несколько расширений. Вы можете ввести powercfg help, чтобы показать эти расширения.
Например, powercfg /energy создает отчет о состоянии батареи в виде HTML-файла, который можно найти по пути: C:\Windows\system32\energy-report.html.
dir – показывает содержимого каталога.
del – удаляет файлы.
attrib +h +s +r имя_папки – скрывает папки. Для отображения папки используйте команду: attrib -h -s -r имя_папки.
start адрес_сайта – открывает сайт из командной строки,
tree – показывает структуру текущего каталога или указанного диска.
ver – отображает версиию ОС.
tasklist – показывает открытые программы.
taskkill – завершает выполнение задачи. Для завершения задачи выполните команду: taskkill /IM «task.exe» /F. Пример: taskkill /IM «chrome.exe» /F.
date – показывает и меняет дату.
time – показывает и меняет время.
vol – выдает серийный номер и информацию о метке текущего накопителя.
dism – запускает средство управления службой образов развертывания.
CTRL + C – прерывает выполнение команды.
-help – выдает справку по командам.
echo – показывает пользовательские сообщения или сообщения из сценария, файла.
Пример создания файла: echo содержимое_файла > имя_файла.расширение.
mkdir – создает папку.
rmdir – удаляет папку. Помните, папка должна быть пустой для успешного удаления.
more – показывает дополнительную информацию или содержимое файла.
move – перемещает файл или папку в указанный каталог.
ren – переименовывает файл. Пример: ren имя_файла.расширение новое_имя.расширение.
cls – очищает командную строку.
exit – закрывает командную строку.
shutdown – завершение работы, перезагрузка, перевод в спящий режим.
Для просмотра доступных опций введите shutdown в командной строке. Например, shutdown /r перезагрузит компьютер.
В итоге
Эта статья познакомила вас с несколькими командами, которые позволяют получить доступ к скрытым функциям вашего ПК. Будьте осторожны при работе с ними, так как они могут оказать длительное воздействие на вашу операционную систему.
CLI (Command Line Interface) — это способ взаимодействия с компьютером через текстовые команды. Вместо того, чтобы кликать по кнопкам, мы вводим команды через терминал (консоль), и система тут же выполняет наши инструкции.
- Отличие от графического интерфейса (GUI)
- В графическом интерфейсе (GUI) мы видим удобные окошки и кнопки, нажимаем мышкой или тачпадом.
- В CLI мы набираем конкретные команды, чаще всего на английском языке, и сразу получаем текстовый результат или вывод.
- CLI считается более гибким и мощным, поскольку позволяет точно управлять системой — одной командой можно сделать то, что в GUI требовало бы целую серию кликов.
- Почему программисту важно уметь работать с консолью
- Скорость. Командой «на лету» можно скопировать десятки файлов, переименовать их, запустить скрипты — всё это занимает секунды.
- Точность и гибкость. У вас полный контроль над системой. Особенно это важно, когда работаете с сервером или автоматизируете рутинные задачи.
- Универсальность. Терминалы бывают везде: на сервере, в облачном окружении, на локальном компьютере. Умение работать в них облегчает жизнь в самых разных проектах.
Представим, что у вас есть куча фотографий с отдыха и их нужно переименовать. Через графический интерфейс придётся вручную переименовывать каждый файл, а через CLI достаточно написать одну команду, и всё будет сделано автоматически!
Главные понятия
Терминал
Работа с командной строкой начинается с терминала.
Открыть терминал
- Linux/Mac: Обычно ищем приложение “Terminal” (или «Терминал») в списке программ. Часто можно запустить его по сочетанию клавиш (например, в Ubuntu — Ctrl+Alt+T).
- Windows:
- CMD (Command Prompt): ищем в поиске Windows «Командная строка» или «cmd».
- PowerShell: ищем «PowerShell» в поиске Windows. Это более современная оболочка, которая поддерживает команды из CMD, но имеет и дополнительные возможности.
Директория (папка) и файл
- Файл — это набор данных, например, текстовый документ, картинка, музыкальный трек.
- Директория (или папка) — это контейнер, в котором лежат файлы и другие папки.
Пример: Есть папка Documents, внутри неё может быть папка Projects, а в ней файлы script.py, notes.txt и т.д.
Путь к файлу/директории
- Абсолютный путь — указывает расположение файла или папки, начиная от корневой директории.
- В Linux/Mac это выглядит, например, как
/home/user/Projects. - В Windows обычно начинается с
C:\Users\Username\Projects.
- В Linux/Mac это выглядит, например, как
- Относительный путь — указывает путь относительно текущей директории.
- Например, если мы уже находимся в
/home/user, то попасть в Projects можно командойcd Projects. - Или
cd ./Projects(точка.указывает на текущую директорию).
- Например, если мы уже находимся в
(Мини-пример)
Вы находитесь в папке/home/user. Абсолютный путь к файлуscript.pyв папкеProjectsбудет/home/user/Projects/script.py. Но если вы уже «внутри»/home/user, то можете набратьcd Projects(относительный путь), а затемpython script.py.
Безопасность и осторожность
Работа с терминалом даёт огромные возможности, но с этим приходит и ответственность:
- Команды, которые могут навредить системе
- Например, команда удаления файлов (в Linux это
rm, а в Windows —delилиRemove-Item) не спросит «А вы точно уверены?», если вы явно не включите такой запрос. А если вы используете параметры вроде-rв Linux (rm -r folder), то можете случайно «снести» целые папки вместе с содержимым! - Важно всегда понимать, где вы находитесь и что удаляете. Ошибка в одной букве пути может привести к катастрофе, если затронуть системные файлы.
- Например, команда удаления файлов (в Linux это
- Как проверить свой текущий путь
- В Linux/Mac достаточно ввести команду
pwd(print working directory). - В Windows можно ввести
echo %cd%(в CMD) илиpwd(в PowerShell). - Эта команда покажет, в какой директории вы сейчас находитесь.
- Привычка перед опасными командами (удаление, перемещение) проверять текущий путь экономит много нервов.
- В Linux/Mac достаточно ввести команду
(Мини-пример)
Вы хотите удалить временные файлы из папки/home/user/temp. Убедитесь, что вы действительно в папке/home/user/temp, введяpwd. Если там всё верно, то используйтеrm *(в Linux) для удаления файлов. Если окажется, что вы внезапно в/home/user/documents, сработает уже другой сценарий — а это не то, что вы хотели!
Небольшое резюме
- CLI — это про гибкость и эффективность.
- Навык навигации по папкам и правильное понимание путей — фундамент для работы в консоли.
- Внимательность: проверяем где мы находимся, что удаляем, и как прописываем команды.
На этом заканчиваем вводную часть. В следующем блоке мы подробнее разберём базовые команды, которые применяются в Linux, Windows и Mac для работы с файлами, папками и прочими элементами системы.
Если остались вопросы, не стесняйтесь задавать! Всякий раз, когда чувствуете, что что-то непонятно, лучше сразу разъяснить и попрактиковаться — так в голове останется меньше «белых пятен», а уверенность в своих силах будет расти.
Как тренироваться в разных операционных системах
Иногда бывает так, что вы хотите учиться работать в Linux, но ваш компьютер — на Windows. Или, наоборот, вы пользуетесь Linux и хотите изучить особенности Windows-команд. К счастью, есть несколько способов «потренироваться» без необходимости менять операционную систему.
Запуск Linux в Windows
- WSL (Windows Subsystem for Linux)
- Начиная с Windows 10, доступна технология WSL. Она позволяет установить дистрибутив Linux (Ubuntu, Debian и другие) прямо внутри Windows и запускать все основные команды в терминале.
- Установка: откройте Microsoft Store, найдите «Ubuntu» (или другой дистрибутив) и установите.
- После установки в меню «Пуск» появится ярлык (например, «Ubuntu»). Запустив его, вы получите полноценный терминал Linux, не покидая Windows.
- Виртуальная машина
- Можно установить популярные программы виртуализации (VirtualBox, VMware Player).
- Скачайте ISO-образ Linux (например, Ubuntu), создайте виртуальную машину и установите систему.
- В итоге у вас будет «второй компьютер в окошке», где можно свободно экспериментировать с командами, не нарушая работу основной системы Windows.
- Live USB
- Если хотите «потрогать» Linux без установки на жёсткий диск, можно создать загрузочную USB-флешку с Linux и загрузиться с неё. При выборе режима «Live» система запустится сразу с флешки.
- Так вы сможете практиковать базовые команды, но при перезагрузке изменения чаще всего не сохраняются (если не настраивать специальный режим постоянного хранения данных).
Запуск Windows в Linux
- Виртуальная машина
- Аналогично, вы можете поставить VirtualBox или VMware на Linux и создать виртуальную машину с Windows (для этого потребуется лицензионный образ Windows).
- Запустив виртуальную машину, вы получите доступ к стандартным Windows-командам через CMD или PowerShell.
- Dual Boot (двойная загрузка)
- Более редкий вариант: установить Windows параллельно с Linux на физический диск. При включении компьютера будет меню выбора ОС. Но это требует знаний о разбивке диска и может быть рискованно, если вы новичок.
Облачные сервисы
Есть и вариант «всё в облаке»:
- Для Linux подойдут бесплатные серверы/машины в облаке (например, различные пробные варианты у хостинг-провайдеров) или в сервисах вроде AWS, Google Cloud, Azure.
- Вы подключаетесь к удалённому серверу через SSH и получаете полноценный терминал Linux, в котором отрабатываете команды.
- Для Windows тоже можно арендовать удалённый сервер (Windows Server), но обычно это платные услуги и чуть сложнее в настройке.
Резюме по тренировке в разных системах
- WSL — самый простой способ при работе в Windows попробовать Linux-команды без суеты с виртуальными машинами.
- VirtualBox/VMware — универсальный метод, работает и для Windows, и для Linux в обе стороны, но требует чуть больше ресурсов (процессор, оперативная память).
- Live USB — отличный «пробный вариант» для знакомства с Linux, не затрагивая жёсткий диск.
- Облачные сервисы — удобно, если нужно учиться работе с серверами или не хочется тратить ресурсы локального ПК.
Таким образом, нет никаких технических препятствий, чтобы практиковаться и в Linux, и в Windows. Выбирайте тот способ, который вам удобнее, и смело осваивайте команды, описанные в уроке!
Общие базовые команды
Навигация по папкам
Когда мы работаем в терминале, нужно уметь быстро и точно переходить в нужную директорию, а также просматривать содержимое папок.
Проверка текущей директории
Linux/Mac
# Показать текущую директорию
pwd
Комментарий:
pwdрасшифровывается как print working directory. Она выводит путь к папке, в которой мы сейчас находимся.
Пример вывода (допустим, мы в домашней папке пользователя anna):
/home/anna
Windows (CMD/PowerShell)
# В CMD
echo %cd%
# В PowerShell
pwd
Комментарий:
- В классической командной строке (CMD) для вывода текущей папки используется переменная окружения
%cd%вместе с командойecho. - В PowerShell можно использовать ту же команду
pwd, что и в Linux/Mac.
Просмотр содержимого директории
Linux/Mac
# Показать список файлов и папок в текущей директории
ls
Комментарий:
- По умолчанию команда
lsвыводит имена всех файлов и подпапок. - Часто используют флаги, например
ls -l, чтобы получить подробную информацию (дата изменения, размер файла и т.д.).
Пример:
ls
Documents Downloads Music Pictures Videos
Windows (CMD/PowerShell)
# Показать список файлов и папок в текущей директории
dir
Комментарий:
- В Windows вместо
lsтрадиционно используетсяdir. - В PowerShell она также работает и даёт аналогичную информацию.
Переход между директориями
Linux/Mac
# Перейти в папку /home/anna/Documents
cd /home/anna/Documents
# Если мы уже находимся в /home/anna,
# то можно сделать относительный переход
cd Documents
Комментарий:
cd(change directory) — сменить директорию.- Абсолютный путь начинается с
/, относительный — от текущей директории.
Windows (CMD/PowerShell)
# Перейти в папку C:\Users\John\Documents
cd C:\Users\John\Documents
# Если мы уже в C:\Users\John,
# то можно использовать относительный путь
cd Documents
Комментарий:
- В Windows пути обычно указываются через обратный слеш
\, но PowerShell и CMD также воспринимают прямой слеш в некоторых случаях.
Практическое упражнение по навигации
- Откройте терминал/командную строку.
- Перейдите в папку загрузок (Downloads) любым из способов:
- Полный путь (например,
cd /home/anna/Downloadsна Linux/Mac илиcd C:\Users\Anna\Downloadsна Windows).- Относительный путь (если вы уже в домашней папке).
- Выведите на экран список файлов в ней с помощью
ls(Linux/Mac) илиdir(Windows).(Дополнительно) Если у вас нет папки Downloads (бывает на некоторых системах), проделайте те же действия с любой другой директорией.
Создание и удаление папок, файлов
Следующий важный шаг — научиться создавать новые папки и файлы, а также их удалять. Тут тоже есть тонкости для разных систем.
Создание папок
Linux/Mac
# Создать папку (директорию) 'test_folder'
mkdir test_folder
Комментарий:
mkdirрасшифровывается как make directory.- Если в папке уже есть
test_folder, команда вернёт ошибку. Можно использовать опцию-p, чтобы избежать ошибок, если родительские папки отсутствуют.
Пример:
mkdir -p my_projects/python_scripts
# Создаст цепочку папок: my_projects, а внутри нее python_scripts
Windows (CMD/PowerShell)
# Создать папку (директорию) 'test_folder'
mkdir test_folder
Комментарий:
- В Windows слово
mkdir(илиmd) работает так же, как в Linux/Mac. - В PowerShell есть разные способы создания папок, но
mkdir— самый простой и привычный.
Создание файлов
Linux/Mac
# Создать (или обновить время модификации) пустой файл 'file.txt'
touch file.txt
Комментарий:
touchсоздаёт пустой файл, если такого ещё нет. Если файл есть, просто обновляет время последнего изменения (в его содержимом ничего не меняется).
Пример (с пояснениями):
touch notes.txt # создаёт пустой файл notes.txt в текущей директории
Windows (CMD)
# Создать пустой файл file.txt (CMD)
type nul > file.txt
Комментарий:
type nulвыводит «ничего»,>перенаправляет этот «вывод» вfile.txt, создавая таким образом пустой файл.
Windows (PowerShell)
# Создать пустой файл file.txt (PowerShell)
New-Item file.txt
Комментарий:
- В PowerShell есть удобная команда
New-Item, которая создаёт файлы и папки. По умолчанию создаёт файл, если не указать иных параметров.
Удаление файлов
Linux/Mac
# Удалить файл file.txt
rm file.txt
Комментарий:
rm(remove) — удаляет файлы. В корзину они не попадают, поэтому будьте осторожны.- Если команда выполнилась успешно — файл исчезает безвозвратно.
Пример:
rm report.docx
# Если файл называется report.docx, он будет удалён
Windows (CMD/PowerShell)
# Удалить файл file.txt
del file.txt
Комментарий:
del— классический вариант удаления файла в CMD.- В PowerShell тоже будет работать команда
del, хотя официально там естьRemove-Item file.txt.
Удаление папок
Linux/Mac
# Удалить папку (директорию) вместе со всем содержимым
rm -r folder_name
Комментарий:
- Флаг
-r(recursive) указывает удалять рекурсивно всё содержимое папки. - Флаг
-f(force) может принудительно удалять без лишних вопросов, но лучше вначале тренироваться без него, чтобы не снести что-нибудь важное случайно.
Windows (CMD)
# Удалить папку folder_name со всем содержимым
rmdir folder_name /s
Комментарий:
/sозначает рекурсивное удаление всех подпапок и файлов.- Windows перед удалением всей папки обычно спросит подтверждение (Y/N).
Windows (PowerShell)
# Удалить папку folder_name со всем содержимым
Remove-Item folder_name -Recurse
Комментарий:
- Параметр
-Recurseуказывает на удаление всего, что находится внутри папки.
Практическое упражнение по созданию и удалению
- Создать новую папку
- Назовите её, например,
my_folder.- Убедитесь, что вы в нужной директории (выполните
pwdили аналог).- Зайти в неё
- С помощью
cd my_folder.- Создать пустой файл
touch my_file.txt(Linux/Mac) илиNew-Item my_file.txt(PowerShell) илиtype nul > my_file.txt(CMD).- Удалить этот файл
rm my_file.txt(Linux/Mac) илиdel my_file.txt(Windows).- Выйти на директорию выше
- В Linux/Mac/Windows используется
cd ..(два раза точка означает “уровень выше”).
(Дополнительно) Попробуйте повторить всё ещё раз, но теперь создайте папку и удалите её целиком. Убедитесь, что делаете это в «учебных» директориях, чтобы не снести важные данные.
Копирование и перемещение файлов
В этом разделе разберём, как скопировать (создать дубликат) или переместить (в том числе переименовать) файлы и папки.
Копирование файлов и папок
Linux/Mac
# Скопировать файл file.txt в backup.txt (создастся копия)
cp file.txt backup.txt
Комментарий:
- Если в директории уже есть backup.txt, он будет перезаписан без предупреждения.
# Копировать папку folder1 в folder2 (рекурсивно)
cp -r folder1 folder2
Комментарий:
- Флаг
-rдаёт команду копировать все файлы внутри folder1.
Windows (CMD/PowerShell)
# Скопировать файл file.txt в backup.txt (CMD/PowerShell)
copy file.txt backup.txt
Комментарий:
- Аналогично перезапишет файл, если backup.txt уже существует.
# Рекурсивно копировать папку folder1 в folder2 (CMD)
xcopy folder1 folder2 /E
Комментарий:
- Параметр
/Eпозволяет копировать и подпапки (включая пустые). - В PowerShell
xcopyтоже доступна, хотя там есть и более современные команды.
Перемещение (и переименование) файлов
Linux/Mac
# Переименовать (или переместить) файл file.txt в new_name.txt
mv file.txt new_name.txt
Комментарий:
- Команда
mv(move) может просто переименовывать файл (если целевая директория совпадает с исходной), либо перемещать (если указываете другую директорию).
# Переместить file.txt в папку Documents (остался старый файл или нет?)
mv file.txt Documents/
Комментарий:
- После выполнения команды, file.txt исчезнет из текущей папки и появится в Documents.
Windows (CMD/PowerShell)
# Переименовать (или переместить) файл file.txt в new_name.txt
move file.txt new_name.txt
Комментарий:
moveработает аналогичноmvв Linux/Mac.
# Переместить file.txt в директорию Documents
move file.txt Documents
Комментарий:
- Если вы в директории, где лежит file.txt, и есть подпапка Documents, файл переместится в неё.
Практическое упражнение по копированию и перемещению
- Создать файл
notes.txt
- Используйте любую команду на выбор (
touch,New-Item,type nul >, и т.д.).- Скопировать его в ту же директорию под именем
notes_copy.txt
- Linux/Mac:
cp notes.txt notes_copy.txt- Windows:
copy notes.txt notes_copy.txt- Создать подпапку
temp
mkdir temp(любая ОС).- Переместить в неё копию файла
- Linux/Mac:
mv notes_copy.txt temp/- Windows:
move notes_copy.txt temp(Дополнительно) Проверьте, что файл действительно переместился. Для этого после перемещения выполните
ls(илиdir) в папкеtempи убедитесь, что там естьnotes_copy.txt.
Выводы и советы
- Не бойтесь экспериментировать, но делайте это в безопасных директориях, где нет важных файлов.
- Автодополнение (Tab) помогает избежать ошибок, когда вы вводите длинные пути или сложные названия.
- Всегда проверяйте текущую директорию (команда
pwdили её эквивалент) перед опасными действиями, чтобы не повредить важные файлы. - Старайтесь систематизировать команды в личном конспекте: выписывать что делает каждая команда, какие есть полезные флаги (
-r,-f,/E,/s,-Recurseи т.д.).
На этом блок с базовыми командами окончен. Когда научитесь уверенно делать все эти операции (переходить, создавать, удалять, копировать, перемещать), вы станете гораздо более «подкованными» пользователями — ведь эти навыки уже дают возможность эффективно управлять файло-структурой на любом компьютере или сервере!
Ниже представлена подробная инструкция по дополнительным утилитам и командам, которые существенно упрощают повседневную работу в терминале. Я разделил их на несколько основных блоков, чтобы материал было проще воспринимать и закреплять на практике.
Дополнительные полезные команды/утилиты
Вывод содержимого файлов
Порой нам нужно быстро заглянуть в текстовый файл, чтобы увидеть его содержимое или проверить, что там написано. Для этого есть специальные команды.
Команда cat (Linux/Mac/PowerShell)
Синтаксис:
cat file.txt
Комментарий:
cat(сокращение от concatenate) читает содержимое файла и выводит его в стандартный вывод (обычно — экран).- Если файл небольшой, вы увидите весь текст сразу. Если файл большой, прокрутка пойдёт очень быстро.
Пример кода:
cat readme.md
# Выведет весь текст из файла readme.md в терминал.
(В PowerShell на Windows, начиная с определённых версий, cat тоже работает как псевдоним для Get-Content. Если не работает, см. ниже о команде type.)
Команда type (Windows CMD)
В классической командной строке Windows (CMD) команда cat не поддерживается, зато есть аналог:
type file.txt
Комментарий:
typeвыводит содержимое файла прямо в окно CMD.- Если файл большой, информация «пролистается» быстро. Можно использовать
type file.txt | more, чтобы построчно пролистывать содержимое.
Тренировочное упражнение
- Создайте небольшой текстовый файл (например,
notes.txt) с помощью любого текстового редактора или консольной команды (echo "Hello CLI" > notes.txtв Linux/PowerShell илиecho Hello CLI > notes.txtв CMD).- Попробуйте вывести его содержимое:
- Linux/Mac:
cat notes.txt- PowerShell:
cat notes.txt(илиGet-Content notes.txt)- CMD:
type notes.txt- (Дополнительно) Измените файл (добавьте несколько строк текста) и снова выведите содержимое, чтобы убедиться, что изменения отображаются сразу.
Создание архивов (Linux/Mac)
В Unix-подобных системах (Linux, Mac) архивы часто создают при помощи утилиты tar. Она умеет не только запаковывать папку в один файл, но и сразу сжимать её (обычно в формат gzip).
Команда tar
Синтаксис:
tar -czf archive.tar.gz folder_name
Комментарий:
-cозначает «создать архив» (create).-zозначает «сжимать с помощью gzip».-fуказывает, что результат будет записан в файл (указываем имяarchive.tar.gz).
Таким образом, команда берёт папку folder_name (и всё её содержимое) и упаковывает в сжатый архив archive.tar.gz.
Пример кода:
tar -czf backup.tar.gz my_project
# Создаст файл backup.tar.gz, который будет содержать всю папку my_project.
Распаковка архива tar.gz
Если нужно разархивировать обратно:
tar -xzf backup.tar.gz
Комментарий:
-x(extract) — извлечь.-z(gzip) и-f(файл), как выше.- По умолчанию распакует файлы в текущую директорию или (если архив содержит абсолютные пути) в соответствующие места.
(Можно задать ключ -C /desired/path, чтобы указать, куда распаковывать.)
Архивирование в Windows
В Windows есть несколько способов:
- PowerShell:
Compress-Archive -Path .\folder_name\* -DestinationPath .\archive.zipКомментарий:
- Параметр
-Pathуказывает, что архивировать, -DestinationPath— куда сохранять.- Обратите внимание, что создаётся архив в формате .zip.
- Параметр
- Сторонние программы: WinRAR, 7-Zip и т.д.
- Чаще всего в Windows используют программы с графическим интерфейсом, но при желании можно найти и консольные утилиты (например, 7z.exe).
Тренировочное упражнение
- Создайте папку
test_archive, поместите внутрь любой файл (например,notes.txt).- Linux/Mac:
- Архивируйте папку командой
tar -czf test_archive.tar.gz test_archive.- Затем удалите папку
test_archiveи разархивируйтеtest_archive.tar.gz, чтобы убедиться, что всё успешно восстановилось.- Windows (PowerShell):
- Выполните
Compress-Archive -Path .\test_archive\* -DestinationPath .\test_archive.zip.- Проверьте, что появился файл
test_archive.zip.- Для распаковки используйте
Expand-Archive -Path .\test_archive.zip -DestinationPath .\extracted_folder, либо обычный графический интерфейс.
Справка по командам
Когда начинаешь изучать новые команды, часто хочется быстро узнать, какие параметры у команды есть, что означает тот или иной флаг и т.д. Для этого в разных системах есть встроенные средства помощи.
man и --help (Linux/Mac)
man ls
Комментарий:
- Запустит подробный мануал (manual) по команде
ls. Откроется текстовая страница с описанием, которую можно пролистывать стрелками или клавишей Space. - Выйти из неё можно, нажав
q.
ls --help
Комментарий:
- Короткая справка по команде
lsс описанием основных флагов. - Аналогичным образом можно попробовать
grep --help,cp --helpи т.д.
help, /?, Get-Help (Windows)
CMD:
help
Комментарий:
- Показывает список доступных команд. Если надо узнать больше о конкретной команде, пишем:
command /?
Например:
dir /?
Комментарий:
- Выведет краткую справку о команде
dirи её параметрах.
PowerShell:
Get-Help ls
Комментарий:
- Отобразит документацию по команде
ls(в PowerShell это алиас, ссылающийся наGet-ChildItem). - Для более подробного вывода можно добавить параметр
-Full.
Тренировочное упражнение
- В Linux/Mac попробуйте команду
ls --help, ознакомьтесь с параметрами. Затем откройте «мануал» —man ls.- В Windows CMD наберите
helpи посмотрите, какие есть стандартные команды. Выберите одну (например,dir) и введитеdir /?, чтобы увидеть все возможные параметры.- В PowerShell сделайте
Get-Help Move-Item, чтобы узнать, как перемещать файлы из консоли PowerShell.(Дополнительно) Поэкспериментируйте с
man tarилиtar --helpв Linux/Mac, и сGet-Help Compress-Archiveв PowerShell, чтобы глубже понять, какие параметры поддерживаются при архивировании.
В этом разделе вы познакомились с несколькими дополнительными командами:
- Просмотр содержимого файла:
cat(Linux/Mac/PowerShell) иtype(Windows CMD). - Архивирование:
tarв Linux/Mac,Compress-Archiveв Windows PowerShell. - Справка:
manи--helpв Linux/Mac,help//?/Get-Helpв Windows.
Все они могут заметно упростить вашу жизнь в консоли, давая возможность быстро пролистывать файлы, делать резервные копии, переносить архивы на другие машины и не «плавать» в опциях команд.
Совет: Даже опытные специалисты регулярно обращаются к встроенной справке, ведь помнить все команды и ключи наизусть невозможно. Чем раньше вы привыкнете к мануалам, тем легче вам будет работать в любой среде.
Оставайтесь любознательными, экспериментируйте и не бойтесь опечатываться — главное, делайте это в безопасном окружении, и всегда проверяйте, в какой директории находитесь, перед тем, как запустить критические команды!
Ниже приводится подробный урок, раскрывающий особенности разных операционных систем. Несмотря на то, что большинство базовых команд и концепций похожи, есть нюансы в путях к файлам и в типах оболочек (shell). В конце каждого раздела вы найдёте тренировочное упражнение, чтобы сразу закрепить знания.
Особенности для разных систем
Различия в путях к файлам/папкам
Путь — это «адрес» к определённому файлу или папке внутри файловой системы. В зависимости от операционной системы, путь может немного отличаться синтаксисом.
Linux/Mac — символ «/»
В Linux и macOS для разделения директорий используется прямой слеш /. Корневая директория (root) обозначается просто /. Абсолютные пути всегда начинаются с /.
Пример абсолютного пути:
# Абсолютный путь к папке Documents в домашней директории пользователя "alex"
/home/alex/Documents
- Здесь
/— корневая директория. - Затем идёт папка
home, внутри неё — папкаalex, а внутриalex— папкаDocuments.
Пример относительного пути:
# Если мы уже находимся в /home/alex, то добраться до папки Documents можно так:
cd Documents
# или
cd ./Documents
- Точка (
.) указывает на текущую директорию. - Две точки (
..) указывают на директорию уровнем выше.
Windows — обратный слеш \ и буквы дисков
В Windows обычно используется обратный слеш \, а также система букс дисков (C:, D: и т.д.).
Пример абсолютного пути:
C:\Users\Alex\Documents
C:— системный диск или просто буква диска.Users\Alex\Documents— цепочка папок.
Пример относительного пути:
# Если мы уже в C:\Users\Alex, можно использовать:
cd Documents
Примечание: В PowerShell зачастую можно использовать и прямые слеши /, но традиционно для Windows принят обратный слеш \.
Тренировочное упражнение
- Если вы работаете в Linux/Mac, попробуйте прописать несколько абсолютных путей, указывая на разные папки (например,
/home/<ваше_имя>/Documents,/home/<ваше_имя>/Downloads). Используйте командуlsилиcdдля проверки, что путь указан верно.- Если вы в Windows, потренируйтесь с абсолютными путями к
C:\Users\<Ваше_имя>\Documentsи относительными путями (например,cd .., чтобы подняться на один уровень выше).- (Дополнительно) Создайте тестовую папку внутри своей домашней директории (имя, например,
demo_folder), перейдите туда с помощью относительного пути и выведите содержимое командойls(в Linux/PowerShell) илиdir(в CMD).
Разные оболочки (shell)
Shell — это программа, которая принимает команды, введённые пользователем, и передаёт их операционной системе для выполнения. По сути, это наш «командный интерпретатор».
Bash, Zsh (Linux/Mac)
В большинстве дистрибутивов Linux по умолчанию стоит Bash (Bourne Again Shell). На macOS в более новых версиях по умолчанию может быть включён Zsh, но суть остаётся схожей.
- Bash: классический shell, встречается во многих системах, имеет большое комьюнити, много готовых скриптов.
- Zsh: похож на Bash, но предлагает ряд дополнительных функций (например, более продвинутую автодополнение). Многие пользователи macOS даже не замечают, что «под капотом» у них Zsh, потому что команды часто совпадают.
Пример использования Bash:
#!/usr/bin/env bash
# Простенький скрипт, который выводит приветствие
echo "Hello from Bash!"
- Первая строка (
#!/usr/bin/env bash) указывает системе, что скрипт должен исполняться через Bash.
CMD и PowerShell (Windows)
В Windows исторически использовалась CMD (Command Prompt), а затем появилась PowerShell, более современная и мощная оболочка:
- CMD: классическая «чёрная консоль» Windows, поддерживает базовые команды вроде
dir,cd,copy. - PowerShell: создана на базе .NET Framework, имеет объектную модель, что делает её очень гибкой. Также поддерживает многие команды и синтаксис, схожие с Unix.
- Если запустить PowerShell и ввести, например,
ls, она сработает, так какlsявляется алиасом дляGet-ChildItem.
Пример использования PowerShell:
# Простой скрипт на PowerShell, выводит сообщение
Write-Host "Hello from PowerShell!"
Write-Hostвыводит сообщение на экран.- Если сохранить этот код в файле
hello.ps1, то запустить можно так:.\hello.ps1(с учётом, что вы в нужной директории).
Тренировочное упражнение
- Linux/Mac:
- Откройте терминал. Выполните команду
echo $SHELL— она покажет, какой shell у вас используется по умолчанию (например,/bin/bashили/bin/zsh).- Создайте простой скрипт
test.sh(внутри напишитеecho "Test Bash script"), сделайте его исполняемым (chmod +x test.sh) и запустите (./test.sh).- Windows:
- Откройте CMD (Command Prompt), выведите список файлов в своей домашней директории командой
dir.- Откройте PowerShell, выполните в ней ту же операцию, но командой
lsилиGet-ChildItem. Сравните вывод.- (Дополнительно) Создайте простой PowerShell-скрипт
hello.ps1, который выводит фразу «Hello PowerShell». Запустите его в PowerShell.- (Универсально) Если хотите «поближе» познакомиться с другой оболочкой, выполните инструкции из предыдущих уроков (например, воспользуйтесь WSL на Windows, чтобы попробовать Bash, или поставьте PowerShell на Linux через пакетный менеджер).
- Пути в Linux/Mac используют прямой слеш
/, а в Windows чаще всего — обратный слеш\и буквы дисков. - Shell — это «среда», через которую мы вводим команды. В Linux/Mac обычно Bash или Zsh, в Windows — CMD или PowerShell.
- Несмотря на то, что базовые действия (создание, удаление, копирование) похожи, синтаксис и набор команд может немного отличаться.
Важнее всего понимать общие концепции: что такое директория, какой путь считается абсолютным, как работает перенаправление команд и т.д. Привыкнув к одной среде, осваивать другую станет гораздо проще.
Не бойтесь практиковаться — попробуйте использовать разные shell и операционные системы, чтобы увидеть, как всё устроено «под капотом»!
Ниже представлен урок с дополнительными советами и рекомендациями, которые помогут вам быстрее освоиться в командной строке и избежать распространённых ошибок. В каждом разделе есть упражнения, позволяющие закрепить теорию на практике.
Дополнительные советы и хорошая практика
Регулярно пользоваться справкой
В каждой операционной системе есть встроенная документация по командам, и это значительно облегчает жизнь, когда вы не помните какой-то флаг или синтаксис.
Linux
man ls
Комментарий:
- Показывает «man-страницу» для команды
ls, где описаны основные параметры, примеры использования. - Чтобы пролистать, используйте клавиши
Стрелка вниз/вверхилиSpace. Закрыть — клавишаq.
ls --help
Комментарий:
- Выводит краткую информацию по использованию команды и параметрам.
Windows
help
Комментарий:
- Показывает в классическом CMD список команд.
dir /?
Комментарий:
- В CMD: даст краткое описание команды
dir. - Аналогично
copy /?,move /?и т.д.
Get-Help Get-ChildItem
Комментарий:
- В PowerShell: показывает справку по команде (в данном случае это команда
Get-ChildItem, которая совпадает с aliasls).
Тренировочное упражнение
- Linux/Mac: откройте терминал и введите
ls --help. Пролистайте выдачу, найдите флаги, которые вам показались интересными (например,-l,-a,-h).- Windows (CMD): введите
dir /?и посмотрите, какие параметры поддерживает командаdir. Попробуйте применить какой-нибудь из них (например,dir /p, чтобы выдача шла постранично).- Windows (PowerShell): выполните
Get-Help Move-Item. Посмотрите примеры снизу страницы, какие форматы записи команды существуют.
Внимательно следить за путями
Указание неправильного пути — одна из самых распространённых ошибок при работе с терминалом. Это может привести к тому, что вы удалите или измените не те файлы.
Команда pwd (Linux/Mac/PowerShell) и echo %cd% (CMD)
pwd
Комментарий:
- Выводит полный путь к текущей директории, где вы сейчас «находитесь».
echo %cd%
Комментарий:
- В CMD для вывода текущего пути.
- В PowerShell вместо этого можно писать
pwd.
Пример ситуации
# Допустим, вы хотите удалить все файлы в папке temp
cd /home/user/temp
rm *
Комментарий:
- Прежде чем запустить
rm *, стоит проверить, что вы действительно находитесь в/home/user/temp(выполнивpwd). - Если вы случайно находились в
/home/user/Documents, то удалите совсем другие файлы!
Тренировочное упражнение
- Создайте новую папку (например,
test_paths), перейдите в неё командойcd test_paths.- Выполните
pwd(Linux/Mac/PowerShell) илиecho %cd%(CMD), чтобы убедиться, что вы «внутри»test_paths.- Создайте в этой папке несколько тестовых файлов (например,
file1.txt,file2.txt).- Выполните удаление (например,
rm file1.txtилиdel file1.txt), убедившись, что стоите вtest_paths. Для проверки перед удалением снова сделайтеpwdилиecho %cd%.
Используйте автодополнение (Tab)
В большинстве оболочек есть возможность автодополнения имён файлов и директорий по нажатию клавиши Tab. Это:
- Экономит время.
- Предотвращает опечатки, так как вам не нужно полностью набирать весь путь.
Пример автодополнения
cd Doc<нажимаем Tab>
Комментарий:
- Если в текущей папке есть
Documents, то при нажатии Tab оболочка автоматически дополнит доDocuments. - Если есть несколько вариантов, которые начинаются на
Doc, shell допишет общую часть и может предложить список вариаций.
cd .\Doc<Tab>
Комментарий:
- Аналогично работает в PowerShell.
- Очень удобно при длинных названиях папок (например,
MyVeryLongDirectoryName).
Тренировочное упражнение
- Перейдите в домашнюю директорию (Linux/Mac:
cd ~, Windows:cd %USERPROFILE%или простоcd, если он настроен).- Начните вводить
cd Docи нажмите Tab. Проверьте, дополнилось ли доDocuments(или какой-то другой папки наDoc).- Если есть несколько папок на
Doc, попробуйте нажимать Tab несколько раз, чтобы перебрать варианты.
Ведите список полезных команд
Когда вы начинаете работать с CLI, полезно записывать где-нибудь (в текстовом файле, бумажном блокноте или заметках на телефоне) те команды и флаги, которые часто применяете.
Пример «списка» в текстовом файле
# Предположим, у нас есть файл commands_cheatsheet.txt
cat commands_cheatsheet.txt
Внутри файла может быть, например:
1) ls -l -> показывает список файлов в длинном формате
2) rm -r -> рекурсивное удаление папки
3) mv file1 file2 -> переименовать или переместить файл1 в файл2
4) cd .. -> подняться на директорию выше
...
Зачем это нужно?
- Поиск информации в личном «шпаргалочном» файле иногда быстрее, чем искать в интернете, особенно если вы знаете, что точно записывали нужную команду.
- Со временем вы выучите 80% необходимых команд наизусть, но всегда останутся редкие случаи, когда запись под рукой сэкономит много времени.
Тренировочное упражнение
- Создайте файл
my_commands.txtв домашней директории.- Запишите туда несколько команд (по одной команде на строчку) с кратким описанием (например,
ls -la — показывает все файлы, включая скрытые, в длинном формате).- Откройте этот файл командой
cat my_commands.txtилиtype my_commands.txt(в CMD) и убедитесь, что всё корректно записано.- (Дополнительно) По желанию, распечатайте этот файл или сохраните его в удобном для вас виде (Google Docs, Evernote и т.п.).
- Справка (man, —help, help, /?, Get-Help) — это первое место, куда надо смотреть при возникновении вопросов о синтаксисе команды.
- Путь к файлу/папке — будьте осторожны и всегда проверяйте, где находитесь, чтобы случайно не изменить или удалить неправильные данные.
- Автодополнение (Tab) позволяет экономить время и защищает от опечаток.
- Личный список команд — ваш путеводитель в мире CLI, особенно в первые недели/месяцы изучения.
Когда овладеете этими «хитростями», процесс работы в командной строке станет легче и приятнее. Опытные пользователи CLI тоже постоянно обращаются к справке, используют автодополнение и ведут шпаргалки — это часть здорового подхода к работе с любым инструментом!
Ниже я добавил дополнительный раздел, посвящённый работе с текстовыми редакторами в среде Linux. Эта тема часто вызывает трудности у новичков, поэтому мы подробно разберём самые популярные консольные редакторы и завершим каждую часть практическим заданием.
Редактор nano: простой и дружелюбный
nano считается самым простым в освоении консольным редактором. Его плюсы:
- Понятный интерфейс, подсказки по ключевым комбинациям внизу экрана.
- Подсветка синтаксиса для многих языков.
- Малое количество режимов (в отличие от vim), поэтому легче адаптироваться новичкам.
Открытие и редактирование файла
nano myfile.txt
Комментарий:
- Если файла
myfile.txtнет, nano создаст его при сохранении. - Внутри редактора вы набираете и редактируете текст, как в обычном блокноте.
Нижняя часть окна отображает комбинации клавиш. Например:
^XозначаетCtrl + X(выход).^OозначаетCtrl + O(сохранение под тем же именем).^WозначаетCtrl + W(поиск текста в файле).
Сохранение и выход
После ввода нужного текста:
- Нажмите
Ctrl + O(буква O, а не ноль). Появится строкаFile Name to Write: myfile.txt. - Нажмите
Enter, чтобы подтвердить сохранение. - Нажмите
Ctrl + X, чтобы выйти из редактора.
Тренировочное упражнение (nano)
- Создайте в терминале новый файл через
nano hello.txt.- Напишите несколько строк, например:
Привет, это мой первый файл в nano!
Я учусь редактировать текст прямо из терминала.
- Сохраните файл (Ctrl + O → Enter) и выйдите (Ctrl + X).
- Убедитесь, что файл создан, выполнив команду
cat hello.txt(илиless hello.txt, если у вас установлен less).
Редактор vim (vi): более «продвинутый» способ
vim (или его предшественник vi) — это очень мощный, но вначале немного «непривычный» редактор, так как использует разные режимы работы.
Основные режимы vim
- Normal mode (обычный режим): здесь вы перемещаетесь по файлу, удаляете и копируете строки и т.д.
- Insert mode (режим вставки): печатаете текст.
- Command mode (командный режим): вводите команды (например, сохранение или выход).
Открытие файла и переход в режим вставки
vim myscript.py
Комментарий:
- Если файла нет, vim создаст его при сохранении.
Внутри vim сразу же включён Normal mode. Чтобы начать ввод текста, нажмите i (insert). Теперь вы в режиме вставки, и все ваши нажатия клавиш пойдут в текст.
Пример:
# Предположим, вы набираете код внутри vim после нажатия i
print("Hello from vim!")
Сохранение и выход
Чтобы сохранить и выйти, нужно вернуться в Normal mode:
- Нажмите
Esc, чтобы выйти из режима вставки. - Введите двоеточие
:(вы переключитесь в командный режим). - Наберите
wq(write & quit) и нажмите Enter.
Результат: vim сохранит файл и выйдет.
Если вы случайно хотите выйти без сохранения, используйте :q!.
Тренировочное упражнение (vim)
- Откройте любой файл (или создайте новый) через
vim new_file.txt.- Нажмите
i, напишите пару строк текста (например, «Ура, я в vim!»).- Нажмите
Esc, затем введите:wq, чтобы сохранить изменения и выйти.- Проверьте результат (например,
cat new_file.txt).(Дополнительно) Попробуйте выйти без сохранения (
:q!) — подойдёт, если вы вдруг ошиблись и не хотите сохранить текущий файл.
Кратко об Emacs (для самых любознательных)
Emacs — ещё один мощный редактор, известный своей расширяемостью (может почти всё, вплоть до встроенного почтового клиента). Но изучать его сразу не обязательно — у него весьма высокая планка входа.
Запуск Emacs в консоли
emacs mynotes.txt
Комментарий:
- Если Emacs установлен, откроется режим редактирования прямо в терминале.
- По умолчанию, Emacs работает в графическом режиме, но при желании можно запустить именно консольный вариант флагом
-nw(no window).
Основные команды в Emacs (без углубления)
Ctrl + x, Ctrl + s(обычно пишутC-x C-s) — сохранить.Ctrl + x, Ctrl + c(C-x C-c) — выход.Ctrl + g(C-g) — отмена текущей команды.
Тренировочное упражнение (Emacs)
- Убедитесь, что Emacs установлен (если нет — возможно, нужно установить через пакетный менеджер, например,
sudo apt-get install emacs).- Запустите
emacs -nw mynotes.txt.- Напишите пару строчек, затем сохраните (
C-x C-s).- Закройте Emacs (
C-x C-c).- Просмотрите файл
mynotes.txtв консоли любым удобным способом (cat,nano,vimи т.д.) для проверки.
Какой редактор выбрать?
- nano: прекрасно подходит начинающим, так как интерфейс прост и нет «сложных» режимов.
- vim: очень мощный инструмент, популярный среди продвинутых пользователей. Однако требует привыкания к модальной системе (Normal / Insert / Command).
- emacs: полноценная среда для «всего». Подойдёт, если вы готовы к длительному погружению и любите расширять редактор под любые задачи.
Рекомендации по выбору
- Если вы только начинаете, лучше учиться на nano: он интуитивнее.
- Освоение vim имеет смысл, если вы часто работаете на серверах, где бывает установлен только
viилиvim. - Emacs — на любителя. Некоторые «фанаты» Emacs используют его как универсальную среду разработки, но это отдельная, более глубокая история.
Тренировочное упражнение (сравнительное)
- Возьмите любой простой файл (например,
test.txt) и последовательно откройте его вnano,vimи, при желании,emacs.- В каждом редакторе сделайте что-нибудь простое: добавьте или удалите пару строк, сохраните и выйдите.
- Сравните, насколько удобно или непривычно пользоваться каждым из редакторов. Определитесь, какой из них вам кажется самым дружелюбным.
Работа с текстовыми файлами из консоли — важная часть освоения Linux. В реальных проектах (на серверах, в облачных средах) зачастую нет графического окружения, так что знать хотя бы один консольный редактор (обычно nano или vim) становится обязательным навыком.
- nano даёт минимальный порог входа: удобно и быстро можно написать/отредактировать конфигурацию, заметку или скрипт.
- vim — сложнее, но зато необычайно гибкий; в нём есть мощная система плагинов и много клавиатурных сокращений для ускорения работы.
- emacs — отдельная вселенная, которая может стать основной рабочей средой для тех, кому нравится расширять возможности редактора.
Попробуйте каждый из них, выполните упражнения и выберите, что подходит лично вам. Но даже если предпочтение отдано nano, советую хотя бы в минимальном объёме освоить vim, так как на многих серверах он предустановлен по умолчанию (и может оказаться вашим единственным вариантом для быстрого редактирования).
Главное — не бояться экспериментировать и учиться новому, ведь навыок работы с консольными редакторами открывает дополнительные возможности для автоматизации и удобного управления системой!
Ниже приводится заключительный урок, в котором мы подводим итоги о важности командной строки (CLI) и рассматриваем, где ещё навыки работы с терминалом могут пригодиться в будущем. Каждая часть завершается коротким тренировочным упражнением, чтобы вы могли закрепить полученные знания в более широком контексте.
Заключение
Эффективность работы разработчика
Работа в консоли даёт много преимуществ:
- Скорость. Часто в CLI можно выполнить действие одной-двумя командами вместо множества кликов в графическом интерфейсе.
- Автоматизация. Написав скрипт, вы сможете многократно запускать его, экономя время на рутинных задачах.
- Точность и контроль. Вы явно указываете, что нужно сделать, и получаете конкретный результат.
Пример сценария
Представьте, что у вас есть сотня фотографий в папке, и вам нужно переименовать их последовательно в img_001.jpg, img_002.jpg, и т.д. В графическом интерфейсе это займёт уйму времени, а в терминале всё делается одной командой (например, с использованием цикла Bash или утилиты rename):
for i in *.jpg; do
# Считаем номер по порядку и формируем новое имя
n=$(printf "%03d" $(echo $((10#${n:-0}+1))))
mv "$i" "img_$n.jpg"
done
Комментарий:
- Этот скрипт перебирает все файлы с расширением
.jpgи переименовывает их, добавляя префиксimg_и номер, форматированный до трёх знаков (001, 002 и т.д.). - Может выглядеть сложновато, но если вы привыкнете к подобным конструкциям, сможете экономить массу времени в реальных проектах.
Тренировочное упражнение (эффективность)
- Создайте папку
images_test, поместите туда несколько файлов (назовите их как угодно, напримерphoto1.jpg,vacation2.jpg,random.jpg).- Напишите мини-скрипт (или командный цикл), который переименует эти файлы в формате
img_001.jpg, img_002.jpgи т.д.- Используйте любую удобную для вас оболочку (Bash, PowerShell). Если вы в Windows, можно установить Git Bash или пользоваться WSL.
(Подсказка: в PowerShell тоже можно использовать цикл
ForEach-Objectилиfor, чтобы перебрать файлы и переименовать их.)
Где ещё полезен CLI?
CLI нужен не только для локальной разработки или навигации по папкам. Список областей, где это крайне полезно, очень широк:
- Настройка серверов:
- Большинство удалённых серверов работают на Linux (Ubuntu, CentOS). Чтобы что-то там настроить, вы будете подключаться по SSH и работать «только через консоль».
- Без знания командной строки придётся сложно.
- Автоматизация задач скриптами:
- Bash-скрипты (Linux/Mac) или PowerShell-скрипты (Windows) позволяют выполнять рутинные операции автоматически (например, копировать резервные копии, генерировать отчёты, мониторить логи).
- Использование Git:
- Git (система контроля версий) можно использовать с графическим интерфейсом, но большинство команд (git clone, git commit, git push) часто удобнее и быстрее делать из консоли.
- Продвинутые возможности Git (rebase, cherry-pick, merge с разными флагами) часто проще освоить именно через CLI, читая документацию.
- DevOps / CI/CD:
- Современные процессы выстраиваются так, что при каждом обновлении кода автоматически запускаются тесты, сборки, деплой. Всё это настраивается в консолях или в виде яml/json-скриптов (например, в GitLab CI, GitHub Actions).
- Умение быстро исправить конфиг в терминале — ключ к оперативному решению проблем.
Пример работы с сервером
# Допустим, вы подключаетесь к удалённому серверу по SSH:
ssh myuser@123.45.67.89
# После ввода пароля или использования ключей,
# вы оказываетесь внутри консоли удалённого сервера.
# Теперь можно смотреть логи, обновлять пакеты, перезапускать сервисы и т.д.
sudo systemctl restart nginx
Комментарий:
- Подключившись к серверу, у вас нет графических «окошек», зато есть вся мощь CLI.
- Если нужно, например, посмотреть, что происходит в журнале веб-сервера:
cat /var/log/nginx/error.logилиtail -f /var/log/nginx/error.log, чтобы видеть обновления журнала в реальном времени.
Пример автоматизации (Bash)
#!/bin/bash
# backup.sh
# Небольшой скрипт, который делает архив папки и складывает в папку backup
SOURCE_DIR="/home/user/my_project"
DEST_DIR="/home/user/backup"
DATE=$(date +%Y-%m-%d_%H-%M-%S)
tar -czf "$DEST_DIR/my_project_$DATE.tar.gz" "$SOURCE_DIR"
echo "Backup completed at $DATE"
Комментарий:
- Запустив этот скрипт командой
./backup.sh, вы упакуете текущую версию проекта в архив с меткой времени. - Можно поставить этот скрипт на cron (планировщик задач в Linux) и сделать бэкапы автоматическими, например, раз в день.
Тренировочное упражнение (где CLI полезен)
- Серверная практика (опционально):
- Если у вас есть доступ к какому-либо удалённому серверу (или вы установили локальную виртуальную машину), подключитесь к ней по SSH и выполните несколько базовых команд (создайте папку, скопируйте файлы, запустите обновление пакетов).
- Git:
- Создайте локальный репозиторий, добавьте файл, сделайте коммит и запушьте на GitHub — всё это через командную строку (
git init,git add,git commit -m,git remote add origin,git push).- Простая автоматизация:
- Напишите маленький скрипт (Bash или PowerShell), который выводит «Hello, world!» и текущее время, затем сохраняйте это в текстовый файл. Запустите скрипт. Проверьте результат.
- CLI открывает огромные возможности: от быстрой навигации по файловой системе и пакетного переименования до настроек серверов и автоматизации процессов.
- Серверная разработка, DevOps, облачные технологии, контроль версий (Git) — всё это на 99% основано на работе через командную строку.
- Эффективность программиста или админа напрямую связана с умением разрулить задачу командой (или несколькими командами) в терминале.
Овладение командной строкой — это не просто «ещё один навык», а «пропуск в мир» системного администрирования, автоматизации и более глубокого понимания, как всё работает «под капотом».
Поздравляем вас с тем, что вы уже освоили большой объём базовых и не очень базовых команд! Продолжайте экспериментировать, читать встроенные мануалы (man, help), писать собственные скрипты и подключаться к новым технологиям — и тогда CLI станет вашим мощным союзником в разработке и администрировании.
Ниже предлагается проектное задание, которое поможет вам отработать все ключевые навыки, полученные в ходе урока по работе с командной строкой (CLI). Задание задумано так, чтобы охватить максимум из пройденных тем: навигацию по директориям, создание и удаление файлов/папок, копирование и перемещение, архивирование, работу со справочными командами, а также базовую автоматизацию и редактирование файлов в терминале. Постарайтесь выполнять его пошагово, проверяя себя после каждого этапа.
Проектное задание: «Создание структуры проекта и автоматизация рутин»
Краткое описание:
Мы создадим «учебный проект» для управления различными файлами, научимся быстро редактировать их, сделаем архивацию, а также познакомимся с простым скриптом для резервного копирования.
Шаг 1: Создание основной директории и базовых подпапок
- Создайте в своей домашней папке (или в любом удобном месте) новую директорию с названием
cli_project.- В Linux/Mac:
mkdir cli_project - В Windows (CMD/PowerShell):
mkdir cli_project
- В Linux/Mac:
- Перейдите в неё:
cd cli_project
- Внутри создайте три подпапки:
docs,scripts,archive.- Например (Linux/Mac):
mkdir docs scripts archive - Или (Windows, CMD/PowerShell):
mkdir docs mkdir scripts mkdir archive
- Например (Linux/Mac):
Результат: у вас должна получиться структура:
cli_project/
├─ docs/
├─ scripts/
└─ archive/
Проверка: выполните ls (Linux/Mac, PowerShell) или dir (CMD) в папке cli_project, убедитесь, что появились три директории.
Шаг 2: Создание и редактирование текстовых файлов
- В папке
docsсоздайте два текстовых файла:commands.txtиnotes.txt.- В Linux/Mac:
cd docs touch commands.txt notes.txt - В Windows (CMD):
cd docs type nul > commands.txt type nul > notes.txt - (PowerShell):
New-Item commands.txt New-Item notes.txt
- В Linux/Mac:
- Откройте
commands.txtв любом консольном редакторе, который удобен вам (nano, vim, emacs или PowerShell ISE/Visual Studio Code, если хотите — но лучше потренироваться именно в консольном редакторе).- Добавьте туда список нескольких команд, которые вы выучили (например,
ls -l,cd ..,rm -rи т. д.) с краткими пояснениями, для чего они нужны.
- Добавьте туда список нескольких команд, которые вы выучили (например,
- Откройте
notes.txtв том же или другом редакторе, напишите заметку, чему вы научились в CLI. - Посмотрите содержимое новых файлов в терминале:
- Linux/Mac/PowerShell:
cat commands.txt,cat notes.txt - CMD:
type commands.txt,type notes.txt
- Linux/Mac/PowerShell:
Проверка: убедитесь, что строки, которые вы добавили, действительно сохранились.
Шаг 3: Копирование и перемещение файлов
- Скопируйте файл
commands.txtиз папкиdocsв папкуarchiveс новым именемcommands_backup.txt.- Пример (Linux/Mac):
cp commands.txt ../archive/commands_backup.txt - Windows (CMD/PowerShell):
copy commands.txt ..\archive\commands_backup.txt
- Пример (Linux/Mac):
- Переместите файл
notes.txtиз папкиdocsв папкуscripts(пусть имя останется прежним).- Linux/Mac:
mv notes.txt ../scripts/ - Windows (CMD/PowerShell):
move notes.txt ..\scripts\
- Linux/Mac:
- Зайдите в папку
archiveи проверьте, что там теперь лежитcommands_backup.txt. Зайдите вscriptsи проверьтеnotes.txt.
Шаг 4: Удаление ненужных файлов
- Вернитесь в папку
docs(если вы не там):cd ../docs - Создайте лишний тестовый файл, например
temp.txt, и удалите его.- В Linux/Mac:
touch temp.txt rm temp.txt - В Windows (CMD):
type nul > temp.txt del temp.txt
- В Linux/Mac:
- Будьте аккуратны и всегда проверяйте командой
pwd(илиecho %cd%в CMD) где вы находитесь, прежде чем удалять файлы.
Шаг 5: Архивация
- Перейдите в корневую папку проекта
cli_project. - Создайте архив из папки
scripts:- Linux/Mac (tar):
tar -czf scripts_archive.tar.gz scriptsТеперь у вас должен появиться файл
scripts_archive.tar.gz. - Windows (PowerShell):
Compress-Archive -Path .\scripts\* -DestinationPath .\scripts_archive.zip
- Linux/Mac (tar):
- Удалите папку
scripts(как будто «освободили» место).- Linux/Mac:
rm -r scripts - Windows (CMD):
rmdir scripts /s - Windows (PowerShell):
Remove-Item scripts -Recurse
- Linux/Mac:
- Извлеките файлы из архива (проверьте, что всё вернулось):
- Linux/Mac:
tar -xzf scripts_archive.tar.gz - Windows (PowerShell):
Expand-Archive -Path .\scripts_archive.zip -DestinationPath .\scripts_restored - При распаковке в Windows может создаться папка
scripts_restored. Вы можете переименовать её обратно вscriptsпри желании.
- Linux/Mac:
Шаг 6: Автоматизация (небольшой скрипт)
- Создайте в папке
scriptsскрипт (назовём егоbackup.shдля Linux/Mac илиbackup.ps1для PowerShell) для резервного копирования папкиdocsвarchive. Пример для Bash:
#!/usr/bin/env bash
# backup.sh - создает архив папки docs с таймстампом
DATE=$(date +%Y-%m-%d_%H-%M-%S)
tar -czf "../archive/docs_backup_$DATE.tar.gz" ../docs
echo "Backup completed: docs_backup_$DATE.tar.gz"
Комментарий:
- Переменная
$DATEберёт текущую дату/время, чтобы каждый архив имел уникальное имя. - Команда
tarсоздаёт gz-архив из содержимого папкиdocsи кладёт его вarchive.
- Сделайте скрипт исполняемым и запустите (Linux/Mac):
cd scripts
chmod +x backup.sh
./backup.sh
- В PowerShell будет похожая идея:
# backup.ps1
# Создаёт zip-архив папки docs с таймстампом
$DATE = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
Compress-Archive -Path ../docs/* -DestinationPath ("../archive/docs_backup_$DATE.zip")
Write-Host "Backup completed: docs_backup_$DATE.zip"
Запуск:
.\backup.ps1
- Проверьте в папке
archive, что создался архив с датой/временем.
Шаг 7: Используйте справку (обязательно!)
Во время выполнения задания:
- Обращайтесь к
man <команда>или--helpв Linux/Mac, - К
help,command /?илиGet-Helpв Windows, - При возникновении затруднений с синтаксисом флагов, ключей и т. п.
(Это не столько шаг, сколько напоминание: регулярно проверяйте документацию.)
Шаг 8: Подведение итогов
- Просмотрите дерево вашего проекта
cli_project:tree cli_project # Linux/Mac (если установлена команда tree)Или с помощью
ls -R cli_project(рекурсивный просмотр). В Windows можно использоватьdir /s cli_project. - Убедитесь, что все операции — создание, удаление, копирование, перемещение, архивирование, а также запуск скриптов — сработали так, как вы планировали.
- Оцените, какие действия вы делали чаще всего, какие команды были самыми полезными. Подумайте, есть ли смысл включить их в свой личный «список полезных команд» или даже написать небольшой шорткат/alias.
Результат проекта
- У вас появился опыт создания и структурирования директории под проект.
- Вы освоили базовые команды CLI в реальном контексте: от навигации и редактирования файлов до архивирования и простых скриптов.
- Вы увидели, как важна аккуратность в указании путей и команд (особенно опасных, вроде удаления).
- У вас есть готовый «скелет» для дальнейших экспериментов — при желании можно расширять проект, добавлять новые скрипты автоматизации, изучать более сложные инструменты.
Дополнительные идеи
- Добавьте Git: Инициализируйте локальный репозиторий в
cli_project(git init), закоммитьте всё, затем сделайте новые коммиты после каждого изменения. - Установите cron (Linux/Mac) или планировщик задач в Windows, чтобы запускать
backup.sh(илиbackup.ps1) автоматически по расписанию. - Подготовьте Dockerfile (если интересно): Создайте контейнер, в котором будет повторяться ваша структура и команды, чтобы всё можно было быстро деплоить на сервер.
Поздравляем с завершением проектного задания! Если вы выполнили все шаги и скрипты работают, значит, вы не только усвоили весь необходимый минимум команд CLI, но и увидели, как они применяются в небольшом, но реальном проектном сценарии. Теперь вы готовы к более продвинутым вещам: настройке серверов, работе с системами контроля версий и профессиональным инструментам автоматизации.
Удачи и успехов в дальнейшем погружении в мир командной строки!
Уровень сложностиПростой
Время на прочтение4 мин
Количество просмотров16K
Краткая предыстория
Когда компьютеры только появились, пользователи общались с ними с помощью текстовых команд. Это так называемый CLI (Command Line Interface) — интерфейс командной строки. Всё, что вы могли сделать — это вводить команды вручную и смотреть результаты их отработки, которые выводились также в виде текста или символов. Например, в 1980-х годах MS-DOS была популярной операционкой, и пользователи должны были знать многие команды наизусть, вроде dir (показать файлы) или copy (скопировать файл), чтобы полноценно работать в ней.
С появлением GUI (Graphical User Interface) всё изменилось. Windows, macOS и другие операционные системы представили графический интерфейс с окнами, кнопками и мышью. Это сделало компьютеры доступными для миллионов людей, которые не хотели запоминать команды. Казалось бы, что «неудобный» CLI должен уйти в прошлое, но этого не произошло до сих пор. Более того, CLI продолжил активное развитие!
GUI + CLI
Сейчас CLI встроен в любую операционную систему, но видеть его использование чаще всего можно в фильмах про хакеров. Для большинства людей работа в интерфейсе командной строки считается «магией», которой владеют лишь «избранные». Вопрос: «В каком интерфейсе проще, лучше и удобнее работать – графическом или интерфейсе командной строки?» — изначально некорректен. А что, если не выбирать между ними, а научиться пользоваться эффективно обоими?
Командная строка — это как суперспособность для тех, кто знает, как её использовать и дальше я попытаюсь вам это доказать на примерах.
CLI в Windows: CMD и PowerShell
Давайте рассмотрим Windows, как самую массовую ось. Для Windows есть два основных инструмента для работы с командной строкой: CMD и PowerShell.
PowerShell — это эволюция CMD. Инструмент сочетает в себе мощь CLI с гибкостью современного языка программирования. Его и будем использовать.
Скачать PowerShell
Хватит лирики, давайте уже рассмотрим примеры. Рассматривая примеры, задумайтесь, сколько бы времени у вас заняло делать эту операцию через графический интерфейс?
Лайфхак!
Если примеры ниже покажутся вам сложными, то это только кажется. Для написания скриптов для PowerShell больше не нужно знать язык программирования. Используйте ChatGPT, GigaChat, любой чат-бот, которым вы уже наверняка пользуетесь: «Напиши мне однострочный скрипт PowerShell, который…» и чат-бот вам быстро выдаст результат.
5 примеров того, как PowerShell может сэкономить вам часы
Пример 1 — Массовое переименование файлов
В графическом интерфейсе каждый файл надо переименовывать отдельно, что долго и муторно. Но есть выход:
Get-ChildItem -Path "C:\Photos" | ForEach-Object { Rename-Item -Path $_.FullName -NewName ("Otpusk_" + $_.Name) }
Скрипт переименует все файлы в папке C:\Photos, добавив к ним префикс «Otpusk_» и это займёт менее 1 сек.
Пример 2 — Поиск и удаление пустых папок
Как это вообще сделать в графическом интерфейсе? В CLI — легко:
Get-ChildItem -Path "C:\Data" -Directory -Recurse | Where-Object { (Get-ChildItem -Path $_.FullName).Count -eq 0 } | Remove-Item -Force
Скрипт найдёт и удалит все пустые папки в C:\Data.
Пример 3 — Поиск файлов по определённым условиям
Поиск в GUI Windows конечно же есть, но мне не нравится скорость его работы и удобство задания условий поиска. Поэтому иногда файлы гораздо быстрее найти с помощью PowerShell:
$yesterday = (Get-Date).AddDays(-1).Date; Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -eq ".docx" -and $_.CreationTime.Date -eq $yesterday } | ForEach-Object { Write-Host "Файл: $($_.FullName), Дата создания: $($_.CreationTime)" }
С этим скриптом вы можете легко и быстро найти все .docx файлы, созданные вчера на диске C. Подобные сценарии актуальны, когда сохранил куда-то файл, а куда — не посмотрел.
Пример 4 — автоматизация каких-то действий
Например, вам нужно в определённой папке найти все jpg размером от 2 Мб до 5 Мб и получить архив с ними в целевой папке. Это можно сделать в GUI, но потребуется сделать несколько действий и при этом есть риск совершить ошибку, отбирая картинки по критериям. Скрипт не ошибётся:
$sourceFolder = "C:\Photos"; $destinationFolder = "C:\FilteredPhotos"; $archivePath = "$destinationFolder\PhotosArchive.zip"; Get-ChildItem -Path $sourceFolder -Recurse -File -Include *.jpg | Where-Object { $_.Length -gt 2MB -and $_.Length -lt 5MB } | Copy-Item -Destination $destinationFolder -Force; Compress-Archive -Path "$destinationFolder\*" -DestinationPath $archivePath -Force; Remove-Item -Path "$destinationFolder\*" -Exclude PhotosArchive.zip -Force
Скрипт в целевой папке (включая подпапки, если они есть) находит jpg по критериям размера (от 2 до 5 МБ), копирует их во временную папку, затем архивирует и удаляет фотки, оставляя только архив.
Пример 5 — управление процессами
Немного специфичный пример, но иногда полезная функция, когда какой-то процесс или процессы забили процессор, от чего компьютер стал тормозить:
Get-Process | Where-Object { $_.CPU -gt 30 } | Stop-Process -Force
Скрипт завершит все процессы, которые используют больше 30% CPU.
Итого
CLI — это не пережиток прошлого, а мощный инструмент, который помогает решать некоторые задачи существенно быстрее и эффективнее, чем если их решать через графический интерфейс. PowerShell позволяет автоматизировать рутину, управлять системой и работать с данными на новом уровне.
Если вы ещё не пробовали PowerShell, самое время начать. Это как получить суперспособность для работы с компьютером.
Это моя первая статья на Хабре. Поддержите меня вашими реакциями и комментариям. Обязательно напишите мне, если данная статья действительно помогла вам сэкономить своё время. У этой статьи будет продолжение о том, как скрипты PowerShell можно сохранять и запускать по расписанию.
Подписывайтесь на мой канал в Телеграм, куда я также буду постить полезный контент!
A command-line interface (CLI) is a means of interacting with software via commands – each formatted as a line of text. Command-line interfaces emerged in the mid-1960s, on computer terminals, as an interactive and more user-friendly alternative to the non-interactive mode available with punched cards.[1]
For a long time, CLI was the most common interface for software, but today the graphical user interface (GUI) is more common. None-the-less, many programs such as operating system and software development utilities still provide CLI.
CLI enables automating programs since commands can be stored in a script file that can be used repeatedly. A script allows its contained commands to be executed as group; as a program; as a command.
CLI is made possible by command-line interpreters or command-line processors, which are programs that execute input commands.
Alternatives to CLI include GUI (including the desktop metaphor such as Windows), text-based menuing (including DOS Shell and IBM AIX SMIT), and keyboard shortcuts.
Comparison to graphical user interfaces
[edit]
Compared with a graphical user interface, a command-line interface requires fewer system resources to implement. Since options to commands are given in a few characters in each command line, an experienced user often finds the options easier to access. Automation of repetitive tasks is simplified by line editing and history mechanisms for storing frequently used sequences; this may extend to a scripting language that can take parameters and variable options. A command-line history can be kept, allowing review or repetition of commands.
A command-line system may require paper or online manuals for the user’s reference, although often a help option provides a concise review of the options of a command. The command-line environment may not provide graphical enhancements such as different fonts or extended edit windows found in a GUI. It may be difficult for a new user to become familiar with all the commands and options available, compared with the icons and drop-down menus of a graphical user interface, without reference to manuals.
Operating system command-line interfaces
[edit]
Operating system (OS) command-line interfaces are usually distinct programs supplied with the operating system. A program that implements such a text interface is often called a command-line interpreter, command processor or shell.
Examples of command-line interpreters include Nushell, DEC’s DIGITAL Command Language (DCL) in OpenVMS and RSX-11, the various Unix shells (sh, ksh, csh, tcsh, zsh, Bash, etc.), CP/M’s CCP, DOS’ COMMAND.COM, as well as the OS/2 and the Windows CMD.EXE programs, the latter groups being based heavily on DEC’s RSX-11 and RSTS CLIs. Under most operating systems, it is possible to replace the default shell program with alternatives; examples include 4DOS for DOS, 4OS2 for OS/2, and 4NT / Take Command for Windows.
Although the term shell is often used to describe a command-line interpreter, strictly speaking, a shell can be any program that constitutes the user interface, including fully graphically oriented ones. For example, the default Windows GUI is a shell program named EXPLORER.EXE, as defined in the SHELL=EXPLORER.EXE line in the WIN.INI configuration file. These programs are shells, but not CLIs.
Application command-line interfaces
[edit]
Application programs (as opposed to operating systems) may also have command-line interfaces.
An application program may support none, any, or all of these three major types of command-line interface mechanisms:
- Parameters: Most command-line interfaces support a means to pass additional information to a program when it is launched.
- Interactive command-line sessions: After launch, a program may provide an operator with an independent means to enter commands.
- Inter-process communication: Most operating systems support means of inter-process communication (for example, standard streams or named pipes). Command lines from client processes may be redirected to a CLI program by one of these methods.
Some applications support a CLI, presenting their own prompt to the user and accepting command lines. Other programs support both a CLI and a GUI. In some cases, a GUI is simply a wrapper around a separate CLI executable file. In other cases, a program may provide a CLI as an optional alternative to its GUI. CLIs and GUIs often support different functionality. For example, all features of MATLAB, a numerical analysis computer program, are available via the CLI, whereas the MATLAB GUI exposes only a subset of features.
In Colossal Cave Adventure from 1975, the user uses a CLI to enter one or two words to explore a cave system.
The command-line interface evolved from a form of communication conducted by people over teleprinter (TTY) machines. Sometimes these involved sending an order or a confirmation using telex. Early computer systems often used teleprinter as the means of interaction with an operator.
The mechanical teleprinter was replaced by a «glass tty», a keyboard and screen emulating the teleprinter. «Smart» terminals permitted additional functions, such as cursor movement over the entire screen, or local editing of data on the terminal for transmission to the computer. As the microcomputer revolution replaced the traditional – minicomputer + terminals – time sharing architecture, hardware terminals were replaced by terminal emulators — PC software that interpreted terminal signals sent through the PC’s serial ports. These were typically used to interface an organization’s new PC’s with their existing mini- or mainframe computers, or to connect PC to PC. Some of these PCs were running Bulletin Board System software.
Early operating system CLIs were implemented as part of resident monitor programs, and could not easily be replaced. The first implementation of the shell as a replaceable component was part of the Multics time-sharing operating system.[2] In 1964, MIT Computation Center staff member Louis Pouzin developed the RUNCOM tool for executing command scripts while allowing argument substitution.[3] Pouzin coined the term shell to describe the technique of using commands like a programming language, and wrote a paper about how to implement the idea in the Multics operating system.[4] Pouzin returned to his native France in 1965, and the first Multics shell was developed by Glenda Schroeder.[3]
The first Unix shell, the V6 shell, was developed by Ken Thompson in 1971 at Bell Labs and was modeled after Schroeder’s Multics shell.[5][6] The Bourne shell was introduced in 1977 as a replacement for the V6 shell. Although it is used as an interactive command interpreter, it was also intended as a scripting language and contains most of the features that are commonly considered to produce structured programs. The Bourne shell led to the development of the KornShell (ksh), Almquist shell (ash), and the popular Bourne-again shell (or Bash).[6]
Early microcomputers themselves were based on a command-line interface such as CP/M, DOS or AppleSoft BASIC. During the 1980s and 1990s, the introduction of the Apple Macintosh and of Microsoft Windows on PCs saw the command line interface as the primary user interface replaced by the Graphical User Interface.[7] The command line remained available as an alternative user interface, often used by system administrators and other advanced users for system administration, computer programming and batch processing.
In November 2006, Microsoft released version 1.0 of Windows PowerShell (formerly codenamed Monad), which combined features of traditional Unix shells with their proprietary object-oriented .NET Framework. MinGW and Cygwin are open-source packages for Windows that offer a Unix-like CLI. Microsoft provides MKS Inc.’s ksh implementation MKS Korn shell for Windows through their Services for UNIX add-on.
Since 2001, the Macintosh operating system macOS has been based on a Unix-like operating system called Darwin.[8] On these computers, users can access a Unix-like command-line interface by running the terminal emulator program called Terminal, which is found in the Utilities sub-folder of the Applications folder, or by remotely logging into the machine using ssh. Z shell is the default shell for macOS; Bash, tcsh, and the KornShell are also provided. Before macOS Catalina, Bash was the default.
A CLI is used whenever a large vocabulary of commands or queries, coupled with a wide (or arbitrary) range of options, can be entered more rapidly as text than with a pure GUI. This is typically the case with operating system command shells. CLIs are also used by systems with insufficient resources to support a graphical user interface. Some computer language systems (such as Python,[9] Forth, LISP, Rexx, and many dialects of BASIC) provide an interactive command-line mode to allow for rapid evaluation of code.
CLIs are often used by programmers and system administrators, in engineering and scientific environments, and by technically advanced personal computer users.[10] CLIs are also popular among people with visual disabilities since the commands and responses can be displayed using refreshable Braille displays.
Anatomy of a shell CLI
[edit]
The general pattern of a command line is:[11][12]
prompt command param1 param2 param3 … paramN
- prompt — output by the program to indicate that its ready for input; a prompt may include contextual information and often ends with a symbol that provides a visual cue that input is expected
- command — input by the user, a command is usually one of two classes:
- Internal commands are recognized and processed by the command line interpreter. Internal commands are also called built-in commands.[13]
- External commands run executables found in separate executable files. The command line interpreter searches for executable files with names matching the external command.[14][15]
- param1 …paramN — parameters provided by the user. The format and meaning of the parameters depends upon the command. In the case of external commands, the values of the parameters are delivered to the program as it is launched by the OS. Parameters may be either arguments or options.
In this format, the delimiters between command-line elements are whitespace characters and the end-of-line delimiter is the newline delimiter. This is a widely used (but not universal) convention.
A CLI can generally be considered as consisting of syntax and semantics. The syntax is the grammar that all commands must follow. In the case of operating systems, DOS and Unix each define their own set of rules that all commands must follow. In the case of embedded systems, each vendor, such as Nortel, Juniper Networks or Cisco Systems, defines their own proprietary set of rules. These rules also dictate how a user navigates through the system of commands. The semantics define what sort of operations are possible, on what sort of data these operations can be performed, and how the grammar represents these operations and data—the symbolic meaning in the syntax.
Two different CLIs may agree on either syntax or semantics, but it is only when they agree on both that they can be considered sufficiently similar to allow users to use both CLIs without needing to learn anything, as well as to enable re-use of scripts.
A simple CLI will display a prompt, accept a command line typed by the user terminated by the Enter key, then execute the specified command and provide textual display of results or error messages. Advanced CLIs will validate, interpret and parameter-expand the command line before executing the specified command, and optionally capture or redirect its output.
Unlike a button or menu item in a GUI, a command line is typically self-documenting,[16] stating exactly what the user wants done. In addition, command lines usually include many defaults that can be changed to customize the results. Useful command lines can be saved by assigning a character string or alias to represent the full command, or several commands can be grouped to perform a more complex sequence – for instance, compile the program, install it, and run it — creating a single entity, called a command procedure or script which itself can be treated as a command. These advantages mean that a user must figure out a complex command or series of commands only once, because they can be saved, to be used again.
The commands given to a CLI shell are often in one of the following forms:
doSomething how toFilesdoSomething how sourceFile destinationFiledoSomething how < inputFile > outputFiledoSomething how | doSomething how | doSomething how > outputFile
where doSomething is, in effect, a verb, how an adverb (for example, should the command be executed verbosely or quietly) and toFiles an object or objects (typically one or more files) on which the command should act. The > in the third example is a redirection operator, telling the command-line interpreter to send the output of the command not to its own standard output (the screen) but to the named file. This will overwrite the file. Using >> will redirect the output and append it to the file. Another redirection operator is the vertical bar (|), which creates a pipeline where the output of one command becomes the input to the next command.[17]
CLI and resource protection
[edit]
One can modify the set of available commands by modifying which paths appear in the PATH environment variable. Under Unix, commands also need be marked as executable files. The directories in the path variable are searched in the order they are given. By re-ordering the path, one can run e.g. \OS2\MDOS\E.EXE instead of \OS2\E.EXE, when the default is the opposite. Renaming of the executables also works: people often rename their favourite editor to EDIT, for example.
The command line allows one to restrict available commands, such as access to advanced internal commands. The Windows CMD.EXE does this. Often, shareware programs will limit the range of commands, including printing a command ‘your administrator has disabled running batch files’ from the prompt.[clarification needed]
Some CLIs, such as those in network routers, have a hierarchy of modes, with a different set of commands supported in each mode. The set of commands are grouped by association with security, system, interface, etc. In these systems the user might traverse through a series of sub-modes. For example, if the CLI had two modes called interface and system, the user might use the command interface to enter the interface mode. At this point, commands from the system mode may not be accessible until the user exits the interface mode and enters the system mode.
«Command prompt» redirects here. For the Windows component named Command Prompt, see cmd.exe.
A command prompt (or just prompt) is a sequence of (one or more) characters used in a command-line interface to indicate readiness to accept commands. It literally prompts the user to take action. A prompt usually ends with one of the characters $, %, #,[18][19] :, > or -[20] and often includes other information, such as the path of the current working directory and the hostname.
On many Unix and derivative systems, the prompt commonly ends in $ or % if the user is a normal user, but in # if the user is a superuser («root» in Unix terminology).
End-users can often modify prompts. Depending on the environment, they may include colors, special characters, and other elements (like variables and functions for the current time, user, shell number or working directory) in order, for instance, to make the prompt more informative or visually pleasing, to distinguish sessions on various machines, or to indicate the current level of nesting of commands. On some systems, special tokens in the definition of the prompt can be used to cause external programs to be called by the command-line interpreter while displaying the prompt.
In DOS’ COMMAND.COM and in Windows NT’s cmd.exe users can modify the prompt by issuing a PROMPT command or by directly changing the value of the corresponding %PROMPT% environment variable. The default of most modern systems, the C:\> style is obtained, for instance, with PROMPT $P$G. The default of older DOS systems, C> is obtained by just PROMPT, although on some systems this produces the newer C:\> style, unless used on floppy drives A: or B:; on those systems PROMPT $N$G can be used to override the automatic default and explicitly switch to the older style.
Many Unix systems feature the $PS1 variable (Prompt String 1),[21] although other variables also may affect the prompt (depending on the shell used). In the Bash shell, a prompt of the form:
[time] user@host: work_dir $
could be set by issuing the command
export PS1='[\t] \u@\H: \W $'
In zsh the $RPROMPT variable controls an optional prompt on the right-hand side of the display. It is not a real prompt in that the location of text entry does not change. It is used to display information on the same line as the prompt, but right-justified.
In RISC OS the command prompt is a * symbol, and thus (OS) CLI commands are often referred to as star commands.[22] One can also access the same commands from other command lines (such as the BBC BASIC command line), by preceding the command with a *.
A command-line argument or parameter is an item of information provided to a program when it is started.[23] A program can have many command-line arguments that identify sources or destinations of information, or that alter the operation of the program.
When a command processor is active a program is typically invoked by typing its name followed by command-line arguments (if any). For example, in Unix and Unix-like environments, an example of a command-line argument is:
file.s is a command-line argument which tells the program rm to remove the file named file.s.
Some programming languages, such as C, C++ and Java, allow a program to interpret the command-line arguments by handling them as string parameters in the main function.[24][25] Other languages, such as Python, expose operating system specific API (functionality) through sys module, and in particular sys.argv for command-line arguments.
In Unix-like operating systems, a single hyphen used in place of a file name is a special value specifying that a program should handle data coming from the standard input or send data to the standard output.
Command-line option
[edit]
A command-line option or simply option (also known as a flag or switch) modifies the operation of a command; the effect is determined by the command’s program. Options follow the command name on the command line, separated by spaces. A space before the first option is not always required, such as Dir/? and DIR /? in DOS, which have the same effect[20] of listing the DIR command’s available options, whereas dir --help (in many versions of Unix) does require the option to be preceded by at least one space (and is case-sensitive).
The format of options varies widely between operating systems. In most cases, the syntax is by convention rather than an operating system requirement; the entire command line is simply a string passed to a program, which can process it in any way the programmer wants, so long as the interpreter can tell where the command name ends and its arguments and options begin.
A few representative samples of command-line options, all relating to listing files in a directory, to illustrate some conventions:
| Operating system | Command | Valid alternative | Notes |
|---|---|---|---|
| OpenVMS | directory/owner |
Dir /Owner |
instruct the directory command to also display the ownership of the files. Note the Directory command name is not case sensitive, and can be abbreviated to as few letters as required to remain unique. |
| Windows | DIR/Q/O:S d* |
dir /q d* /o:s |
display ownership of files whose names begin with d (or D), sorted by size, smallest first. Note spaces around argument d* are required. |
| Unix-like systems | ls -lS D* |
ls -S -l D* |
display in long format files and directories whose names begin with D (but not d), sorted by size (largest first). Note spaces are required around all arguments and options, but some can be run together, e.g. -lS is the same as -l -S. |
| Data General RDOS CLI | list/e/s 04-26-80/b |
List /S/E 4-26-80/B |
list every attribute for files created before 26 April 1980. Note the /B at the end of the date argument is a local switch, that modifies the meaning of that argument, while /S and /E are global switches, i.e. apply to the whole command. |
| VM/CMS CLI | LISTFILE (FULLDATE) |
l(ful |
includes the date the file was last written in the list. Note the LISTFILE command name is not case sensitive, and can be abbreviated to as few letters as required to remain unique. |
Abbreviating commands
[edit]
In Multics, command-line options and subsystem keywords may be abbreviated. This idea appears to derive from the PL/I programming language, with its shortened keywords (e.g., STRG for STRINGRANGE and DCL for DECLARE). For example, in the Multics forum subsystem, the -long_subject parameter can be abbreviated -lgsj. It is also common for Multics commands to be abbreviated, typically corresponding to the initial letters of the words that are strung together with underscores to form command names, such as the use of did for delete_iacl_dir.
In some other systems abbreviations are automatic, such as permitting enough of the first characters of a command name to uniquely identify it (such as SU as an abbreviation for SUPERUSER) while others may have some specific abbreviations pre-programmed (e.g. MD for MKDIR in COMMAND.COM) or user-defined via batch scripts and aliases (e.g. alias md mkdir in tcsh).
Option conventions in DOS, Windows, OS/2
[edit]
On DOS, OS/2 and Windows, different programs called from their COMMAND.COM or CMD.EXE (or internal their commands) may use different syntax within the same operating system. For example:
- Options may be indicated by either of the switch characters:
/,-, or either may be allowed. See below. - They may or may not be case-sensitive.
- Sometimes options and their arguments are run together, sometimes separated by whitespace, and sometimes by a character, typically
:or=; thusProg -fFilename,Prog -f Filename,Prog -f:Filename,Prog -f=Filename. - Some programs allow single-character options to be combined;[20] others do not. The switch
-fAmay mean the same as-f -A,[20] or it may be incorrect, or it may even be a valid but different parameter.
In DOS, OS/2 and Windows, the forward slash (/) is most prevalent, although the hyphen-minus is also sometimes used. In many versions of DOS (MS-DOS/PC DOS 2.xx and higher, all versions of DR-DOS since 5.0, as well as PTS-DOS, Embedded DOS, FreeDOS and RxDOS) the switch character (sometimes abbreviated switchar or switchchar) to be used is defined by a value returned from a system call (INT 21h/AX=3700h). The default character returned by this API is /, but can be changed to a hyphen-minus on the above-mentioned systems, except for under Datalight ROM-DOS and MS-DOS/PC DOS 5.0 and higher, which always return / from this call (unless one of many available TSRs to reenable the SwitChar feature is loaded). In some of these systems (MS-DOS/PC DOS 2.xx, DOS Plus 2.1, DR-DOS 7.02 and higher, PTS-DOS, Embedded DOS, FreeDOS and RxDOS), the setting can also be pre-configured by a SWITCHAR directive in CONFIG.SYS. General Software’s Embedded DOS provides a SWITCH command for the same purpose, whereas 4DOS allows the setting to be changed via SETDOS /W:n.[26] Under DR-DOS, if the setting has been changed from /, the first directory separator \ in the display of the PROMPT parameter $G will change to a forward slash / (which is also a valid directory separator in DOS, FlexOS, 4680 OS, 4690 OS, OS/2 and Windows) thereby serving as a visual clue to indicate the change.[20] Also, the current setting is reflected also in the built-in help screens.[20] Some versions of DR-DOS COMMAND.COM also support a PROMPT token $/ to display the current setting. COMMAND.COM since DR-DOS 7.02 also provides a pseudo-environment variable named %/% to allow portable batchjobs to be written.[27][28] Several external DR-DOS commands additionally support an environment variable %SWITCHAR% to override the system setting.
However, many programs are hardwired to use / only, rather than retrieving the switch setting before parsing command-line arguments. A very small number, mainly ports from Unix-like systems, are programmed to accept - even if the switch character is not set to it (for example netstat and ping, supplied with Microsoft Windows, will accept the /? option to list available options, and yet the list will specify the - convention).
Option conventions in Unix-like systems
[edit]
In Unix-like systems, the ASCII hyphen-minus begins options; the new (and GNU) convention is to use two hyphens then a word (e.g. --create) to identify the option’s use while the old convention (and still available as an option for frequently-used options) is to use one hyphen then one letter (e.g., -c); if one hyphen is followed by two or more letters it may mean two options are being specified, or it may mean the second and subsequent letters are a parameter (such as filename or date) for the first option.[29]
Two hyphen-minus characters without following letters (--) may indicate that the remaining arguments should not be treated as options, which is useful for example if a file name itself begins with a hyphen, or if further arguments are meant for an inner command (e.g., sudo). Double hyphen-minuses are also sometimes used to prefix long options where more descriptive option names are used. This is a common feature of GNU software. The getopt function and program, and the getopts command are usually used for parsing command-line options.
Unix command names, arguments and options are case-sensitive (except in a few examples, mainly where popular commands from other operating systems have been ported to Unix).
Option conventions in other systems
[edit]
FlexOS, 4680 OS and 4690 OS use -.
CP/M typically used [.
Conversational Monitor System (CMS) uses a single left parenthesis to separate options at the end of the command from the other arguments. For example, in the following command the options indicate that the target file should be replaced if it exists, and the date and time of the source file should be retained on the copy:
COPY source file a target file b (REPLACE OLDDATE)
Data General’s CLI under their RDOS, AOS, etc. operating systems, as well as the version of CLI that came with their Business Basic, uses only / as the switch character, is case-insensitive, and allows local switches on some arguments to control the way they are interpreted, such as MAC/U LIB/S A B C $LPT/L has the global option U to the macro assembler command to append user symbols, but two local switches, one to specify LIB should be skipped on pass 2 and the other to direct listing to the printer, $LPT.
Built-in usage help
[edit]
One of the criticisms of a CLI is the lack of cues to the user as to the available actions.[citation needed] In contrast, GUIs usually inform the user of available actions with menus, icons, or other visual cues.[citation needed] To overcome this limitation, many CLI programs display a usage message, typically when invoked with no arguments or one of ?, -?, -h, -H, /?, /h, /H, /Help, -help, or --help.[20][30][31]
However, entering a program name without parameters in the hope that it will display usage help can be hazardous, as programs and scripts for which command line arguments are optional will execute without further notice.
Although desirable at least for the help parameter, programs may not support all option lead-in characters exemplified above.
Under DOS, where the default command-line option character can be changed from / to -, programs may query the SwitChar API in order to determine the current setting. So, if a program is not hardwired to support them all, a user may need to know the current setting even to be able to reliably request help.
If the SwitChar has been changed to - and therefore the / character is accepted as alternative path delimiter also at the DOS command line, programs may misinterpret options like /h or /H as paths rather than help parameters.[20] However, if given as first or only parameter, most DOS programs will, by convention, accept it as request for help regardless of the current SwitChar setting.[20][26]
In some cases, different levels of help can be selected for a program. Some programs supporting this allow to give a verbosity level as an optional argument to the help parameter (as in /H:1, /H:2, etc.) or they give just a short help on help parameters with question mark and a longer help screen for the other help options.[32]
Depending on the program, additional or more specific help on accepted parameters is sometimes available by either providing the parameter in question as an argument to the help parameter or vice versa (as in /H:W or in /W:? (assuming /W would be another parameter supported by the program)).[33][34][31][30][32][nb 1]
In a similar fashion to the help parameter, but much less common, some programs provide additional information about themselves (like mode, status, version, author, license or contact information) when invoked with an about parameter like -!, /!, -about, or --about.[30]
Since the ? and ! characters typically also serve other purposes at the command line, they may not be available in all scenarios, therefore, they should not be the only options to access the corresponding help information.
If more detailed help is necessary than provided by a program’s built-in internal help, many systems support a dedicated external help command» command (or similar), which accepts a command name as calling parameter and will invoke an external help system.
In the DR-DOS family, typing /? or /H at the COMMAND.COM prompt instead of a command itself will display a dynamically generated list of available internal commands;[20] 4DOS and NDOS support the same feature by typing ? at the prompt[26] (which is also accepted by newer versions of DR-DOS COMMAND.COM); internal commands can be individually disabled or reenabled via SETDOS /I.[26] In addition to this, some newer versions of DR-DOS COMMAND.COM also accept a ?% command to display a list of available built-in pseudo-environment variables. Besides their purpose as quick help reference this can be used in batchjobs to query the facilities of the underlying command-line processor.[20]
Command description syntax
[edit]
Built-in usage help and man pages commonly employ a small syntax to describe the valid command form:[35][36][37][nb 2]
- angle brackets for required parameters:
ping <hostname> - square brackets for optional parameters:
mkdir [-p] <dirname> - ellipses for repeated items:
cp <source1> [source2…] <dest> - vertical bars for choice of items:
netstat {-t|-u}
Notice that these characters have different meanings than when used directly in the shell. Angle brackets may be omitted when confusing the parameter name with a literal string is not likely.
The space character
[edit]
In many areas of computing, but particularly in the command line, the space character can cause problems as it has two distinct and incompatible functions: as part of a command or parameter, or as a parameter or name separator. Ambiguity can be prevented either by prohibiting embedded spaces in file and directory names in the first place (for example, by substituting them with underscores _), or by enclosing a name with embedded spaces between quote characters or using an escape character before the space, usually a backslash (\). For example
Long path/Long program name Parameter one Parameter two…
is ambiguous (is program name part of the program name, or two parameters?); however
Long_path/Long_program_name Parameter_one Parameter_two…,LongPath/LongProgramName ParameterOne ParameterTwo…,"Long path/Long program name" "Parameter one" "Parameter two"…
and
Long\ path/Long\ program\ name Parameter\ one Parameter\ two…
are not ambiguous. Unix-based operating systems minimize the use of embedded spaces to minimize the need for quotes. In Microsoft Windows, one often has to use quotes because embedded spaces (such as in directory names) are common.
Command-line interpreter
[edit]
Although most users think of the shell as an interactive command interpreter, it is really a programming language in which each statement runs a command. Because it must satisfy both the interactive and programming aspects of command execution, it is a strange language, shaped as much by history as by design.
The term command-line interpreter is applied to computer programs designed to interpret a sequence of lines of text which may be entered by a user, read from a file or another kind of data stream. The context of interpretation is usually one of a given operating system or programming language.
Command-line interpreters allow users to issue various commands in a very efficient (and often terse) way. This requires the user to know the names of the commands and their parameters, and the syntax of the language that is interpreted.
The Unix #! mechanism and OS/2 EXTPROC command facilitate the passing of batch files to external processors. One can use these mechanisms to write specific command processors for dedicated uses, and process external data files which reside in batch files.
Many graphical interfaces, such as the OS/2 Presentation Manager and early versions of Microsoft Windows use command lines to call helper programs to open documents and programs. The commands are stored in the graphical shell[clarification needed] or in files like the registry or the OS/2 OS2USER.INI file.
The earliest computers did not support interactive input/output devices, often relying on sense switches and lights to communicate with the computer operator. This was adequate for batch systems that ran one program at a time, often with the programmer acting as operator. This also had the advantage of low overhead, since lights and switches could be tested and set with one machine instruction. Later a single system console was added to allow the operator to communicate with the system.
From the 1960s onwards, user interaction with computers was primarily by means of command-line interfaces, initially on machines like the Teletype Model 33 ASR, but then on early CRT-based computer terminals such as the VT52.
All of these devices were purely text based, with no ability to display graphic or pictures.[nb 3] For business application programs, text-based menus were used, but for more general interaction the command line was the interface.
Around 1964 Louis Pouzin introduced the concept and the name shell in Multics, building on earlier, simpler facilities in the Compatible Time-Sharing System (CTSS).[39][better source needed]
From the early 1970s the Unix operating system adapted the concept of a powerful command-line environment, and introduced the ability to pipe the output of one command in as input to another. Unix also had the capability to save and re-run strings of commands as shell scripts which acted like custom commands.
The command line was also the main interface for the early home computers such as the Commodore PET, Apple II and BBC Micro – almost always in the form of a BASIC interpreter. When more powerful business-oriented microcomputers arrived with CP/M and later DOS computers such as the IBM PC, the command line began to borrow some of the syntax and features of the Unix shells such as globbing and piping of output.
The command line was first seriously challenged by the PARC GUI approach used in the 1983 Apple Lisa and the 1984 Apple Macintosh. A few computer users used GUIs such as GEOS and Windows 3.1 but the majority of IBM PC users did not replace their COMMAND.COM shell with a GUI until Windows 95 was released in 1995.[40][41]
Modern usage as an operating system shell
[edit]
While most non-expert computer users now use a GUI almost exclusively, more advanced users have access to powerful command-line environments:
- The default VAX/VMS command shell, using the DCL language, has been ported to Windows systems at least three times, including PC-DCL and Acceler8 DCL Lite. Unix command shells have been ported to VMS and DOS/Windows 95 and Windows NT types of operating systems.
- COMMAND.COM is the command-line interpreter of MS-DOS, IBM PC DOS, and clones such as DR-DOS, SISNE plus, PTS-DOS, ROM-DOS, and FreeDOS.
- Windows Resource Kit and Windows Services for UNIX include Korn and the Bourne shells along with a Perl interpreter (Services for UNIX contains ActiveState ActivePerl in later versions and Interix for versions 1 and 2 and a shell compiled by Microsoft)
- IBM OS/2 (and derivatives such as eComStation and ArcaOS) has the cmd.exe processor. This copies the COMMAND.COM commands, with extensions to REXX.
- cmd.exe is part of the Windows NT stream of operating systems.
- Yet another cmd.exe is a stripped-down shell for Windows CE 3.0.
- An MS-DOS type interpreter called PocketDOS has been ported to Windows CE machines; the most recent release is almost identical to MS-DOS 6.22 and can also run Windows 1, 2, and 3.0, QBasic and other development tools, 4NT and 4DOS. The latest release includes several shells, namely MS-DOS 6.22, PC DOS 7, DR DOS 3.xx, and others.
- Windows users might use the CScript interface to alternate programs, from the command line. PowerShell provides a command-line interface, but its applets are not written in Shell script. Implementations of the Unix shell are also available as part of the POSIX sub-system,[42] Cygwin, MKS Toolkit, UWIN, Hamilton C shell and other software packages. Available shells for these interoperability tools include csh, ksh, sh, Bash, rsh, tclsh and less commonly zsh, psh
- Implementations of PHP have a shell for interactive use called php-cli.
- Standard Tcl/Tk has two interactive shells, Tclsh and Wish, the latter being the GUI version.
- Python, Ruby, Lua, XLNT, and other interpreters also have command shells for interactive use.
- FreeBSD uses tcsh as its default interactive shell for the superuser, and ash as default scripting shell.
- Many Linux distributions have the Bash implementation of the Unix shell.
- Apple macOS and some Linux distributions use zsh. Previously, macOS used tcsh and Bash.
- Embedded Linux (and other embedded Unix-like) devices often use the Ash implementation of the Unix shell, as part of Busybox.
- Android uses the mksh shell,[43][44] which replaces a shell derived from ash[45] that was used in older Android versions, supplemented with commands from the separate toolbox[46] binary.
- HarmonyOS, OpenHarmony and Oniro uses the commands from third party toolbox compatibility system attached to Linux kernel of the subsystem alongside default Shell with exec commands.[47][48]
- Routers with Cisco IOS,[49] Junos[50] and many others are commonly configured from the command line.
- The Plan 9 operating system uses the rc shell, which is similar in design to the Bourne shell.
Most command-line interpreters support scripting, to various extents. (They are, after all, interpreters of an interpreted programming language, albeit in many cases the language is unique to the particular command-line interpreter.) They will interpret scripts (variously termed shell scripts or batch files) written in the language that they interpret. Some command-line interpreters also incorporate the interpreter engines of other languages, such as REXX, in addition to their own, allowing the executing of scripts, in those languages, directly within the command-line interpreter itself.
Conversely, scripting programming languages, in particular those with an eval function (such as REXX, Perl, Python, Ruby or Jython), can be used to implement command-line interpreters and filters. For a few operating systems, most notably DOS, such a command interpreter provides a more flexible command-line interface than the one supplied. In other cases, such a command interpreter can present a highly customised user interface employing the user interface and input/output facilities of the language.
Other command-line interfaces
[edit]
The command line provides an interface between programs as well as the user. In this sense, a command line is an alternative to a dialog box. Editors and databases present a command line, in which alternate command processors might run. On the other hand, one might have options on the command line, which opens a dialog box. The latest version of ‘Take Command’ has this feature. DBase used a dialog box to construct command lines, which could be further edited before use.
Programs like BASIC, diskpart, Edlin, and QBASIC all provide command-line interfaces, some of which use the system shell. Basic is modeled on the default interface for 8-bit Intel computers. Calculators can be run as command-line or dialog interfaces.
Emacs provides a command-line interface in the form of its minibuffer. Commands and arguments can be entered using Emacs standard text editing support, and output is displayed in another buffer.
There are a number of text mode games, like Adventure or King’s Quest 1-3, which relied on the user typing commands at the bottom of the screen. One controls the character by typing commands like ‘get ring’ or ‘look’. The program returns a text which describes how the character sees it, or makes the action happen. The text adventure The Hitchhiker’s Guide to the Galaxy, a piece of interactive fiction based on Douglas Adam’s book of the same name, is a teletype-style command-line game.
The most notable of these interfaces is the standard streams interface, which allows the output of one command to be passed to the input of another. Text files can serve either purpose as well. This provides the interfaces of piping, filters and redirection. Under Unix, devices are files too, so the normal type of file for the shell used for stdin, stdout and stderr is a tty device file.
Another command-line interface allows a shell program to launch helper programs, either to launch documents or start a program. The command is processed internally by the shell, and then passed on to another program to launch the document. The graphical interface of Windows and OS/2 rely heavily on command lines passed through to other programs – console or graphical, which then usually process the command line without presenting a user-console.
Programs like the OS/2 E editor and some other IBM editors, can process command lines normally meant for the shell, the output being placed directly in the document window.
A web browser’s URL input field can be used as a command line. It can be used to launch web apps, access browser configuration, as well as perform a search. Google, which has been called «the command line of the internet» will perform a domain-specific search when it detects search parameters in a known format.[51] This functionality is present whether the search is triggered from a browser field or on Google’s website.
There are JavaScript libraries that allow to write command line applications in browser as standalone Web apps or as part of bigger application.[52] An example of such a website is the CLI interface to DuckDuckGo.[53] There are also Web-based SSH applications, that allow to give access to server command line interface from a browser.
Many PC video games feature a command line interface often referred to as a console. It is typically used by the game developers during development and by mod developers for debugging purposes as well as for cheating or skipping parts of the game.
- Comparison of command shells
- List of command-line interpreters
- Console application
- Interpreter directive
- Read-eval-print loop
- Shell script
- Run command
- Graphical user interface § Comparison to other interfaces
- In the Beginning… Was the Command Line
- ^ An example is the comprehensive internal help system of the DR-DOS 7.03 DEBUG command, which can be invoked via
??at the debug prompt (rather than only the default?overview). Specific help pages can be selected via?n(wherenis the number of the page). Additionally, help for specific commands can be displayed by specifying the command name after?, f.e.?Dwill invoke help for the various dump commands (likeDetc.). Some of these features were already supported by the DR DOS 3.41 SID86 and GEMSID. - ^ Notable difference for describing the command syntax of DOS-like operating systems: Windows Server 2003 R2 documentation uses italic letters for «information that the user must supply», but Windows Server 2008 documentation uses angle brackets. Italics can not be displayed by the internal help command, while there is no problem with angle brackets.
- ^ With the exception of ASCII art.
- ^ «The evolution of command line interface (CLI): A historical insight | Contentstack». www.contentstack.com. Retrieved 2025-01-28.
- ^ «Unix Shells». Archived from the original on 2007-11-08.
the notion of having a replaceable «command shell» rather than a «monitor» tightly integrated with the OS kernel tends to be attributed to Multics.
- ^ a b «The Origin of the Shell». www.multicians.org. Archived from the original on 2017-12-21. Retrieved 2017-04-12.
- ^ Metz, Cade (2013-01-03). «Say Bonjour to the Internet’s Long-Lost French Uncle». Wired. Retrieved 2017-07-31.
- ^ Mazières, David (Fall 2004). «MULTICS — The First Seven Years». Advanced Operating Systems. Stanford Computer Science Department. Archived from the original on 2014-11-23. Retrieved 2017-08-01.
- ^ a b Jones, M. (2011-12-06). «Evolution of shells in Linux». developerWorks. IBM. Archived from the original on 2017-07-08. Retrieved 2017-08-01.
- ^ «Graphical User Interface History». KASS. Retrieved 2024-03-24.
- ^ Singh, Amit (2006-06-19). Mac OS X Internals: A Systems Approach. Addison-Wesley Professional. ISBN 978-0-13-270226-3.
- ^ «1. Command line and environment». Python documentation. Retrieved 2024-08-05.
- ^ «What is a CLI? — Command Line Interface Explained — AWS». Amazon Web Services, Inc. Retrieved 2025-01-28.
- ^ «GNU BASH Reference». Archived from the original on 2010-12-03. Retrieved 2015-12-20.
- ^ «Microsoft Windows Command Shell Overview». 2009-09-11. Archived from the original on 2015-09-05. Retrieved 2015-07-12.
- ^ «Shell Built-in Commands List». Linux Handbook. 2023-07-05. Retrieved 2024-08-05.
- ^ B, Jason. «How to set your $PATH variable in Linux | Opensource.com». opensource.com. Retrieved 2024-08-05.
- ^ JasonGerend (2023-02-03). «path». learn.microsoft.com. Retrieved 2024-08-05.
- ^ «Command Line Interface (CLI)». tutorials.cloudfoundry.org. Retrieved 2025-01-28.
- ^ «Learning the bash Shell, Second Edition [Book]». www.oreilly.com. Retrieved 2024-08-05.
- ^ SID Users Guide (PDF). Digital Research. 1978. 595-2549. Archived (PDF) from the original on 2019-10-20. Retrieved 2020-02-06. (4+69 pages)
- ^ SID-86 User’s Guide for CP/M-86 (2 ed.). Digital Research. August 1982 [March 1982]. SID86UG.WS4. Archived from the original on 2019-10-20. Retrieved 2020-02-06. [1] (NB. A retyped version of the manual by Emmanuel Roche with Q, SR, and Z commands added.)
- ^ a b c d e f g h i j k Paul, Matthias R. (1997-07-30). «NWDOS-TIPs – Tips & Tricks rund um Novell DOS 7, mit Blick auf undokumentierte Details, Bugs und Workarounds». MPDOSTIP. Release 157 (in German) (3 ed.). Archived from the original on 2017-09-10. Retrieved 2014-09-06. (NB. NWDOSTIP.TXT is a comprehensive work on Novell DOS 7 and OpenDOS 7.01, including the description of many undocumented features and internals. It is part of the author’s yet larger MPDOSTIP.ZIP collection maintained up to 2001 and distributed on many sites at the time. The provided link points to a HTML-converted older version of the NWDOSTIP.TXT file.)
- ^ Parker, Steve (2011). «Chapter 11: Choosing and using shells». Shell Scripting: Expert Recipes for Linux, Bash and more. Programmer to programmer. Indianapolis, USA: John Wiley & Sons. p. 262. ISBN 978-111816632-1.
The shell has four different command prompts, called PS1, P52, P53, and PS4. PS stands for Prompt String.
- ^ RISC OS 3 User Guide (PDF). Acorn Computers Limited. 1992-03-01. p. 125. Archived (PDF) from the original on 2017-01-09. Retrieved 2017-04-12.
- ^ nguyen-dows (2024-05-29). «Windows Terminal command line arguments». learn.microsoft.com. Retrieved 2024-08-05.
- ^ «Command Line Arguments in C». www.w3schools.in. Retrieved 2024-08-05.
- ^ «Command Line Arguments in Java». GeeksforGeeks. 2016-08-16. Retrieved 2024-08-05.
- ^ a b c d Brothers, Hardin; Rawson, Tom; Conn, Rex C.; Paul, Matthias R.; Dye, Charles E.; Georgiev, Luchezar I. (2002-02-27). 4DOS 8.00 online help.
- ^ Paul, Matthias R. (1998-01-09). DELTREE.BAT R1.01 Extended file and directory delete. Caldera, Inc. Archived from the original on 2019-04-08. Retrieved 2019-04-08.
- ^ DR-DOS 7.03 WHATSNEW.TXT — Changes from DR-DOS 7.02 to DR-DOS 7.03. Caldera, Inc. 1998-12-24. Archived from the original on 2019-04-08. Retrieved 2019-04-08.
- ^ «Argument Syntax (The GNU C Library)». gnu.org. Archived from the original on 2021-06-18. Retrieved 2021-07-09.
- ^ a b c Paul, Matthias R. (2002-05-13). «[fd-dev] mkeyb». freedos-dev. Archived from the original on 2018-09-10. Retrieved 2018-09-10.
[…] CPI /H […] CPI [@] [@] [/?|/Help[:topic]] [/!|/About] […] [?|&] […] /?, /Help Display this help screen or specific help for a topic (+) […] /!, /About Display the ‘About’ info screen […] /Cpifile (+) .CPI/.CP file name <EGA.CPI>; extension: <.CPI>; CPI.EXE=StdIn […] /Report Report file name <‘
‘=StdOut>; extension: <.RPT> […] /Style (+) Export <0>-6=BIN-raw/ROM/RAM/PSF0/1/SH/CHED; 7-12/13-18/19-24=ASM-hex/dec/bin/ip/il/p/l/mp/ml […] CPI /H:C […] Overview on codepage file parameter usage: […] CPI /H:S […] Overview on /Style parameters: […] ?, & Online edit mode (prompts for additional parameter input) […] - ^ a b Paul, Matthias R. (2002-01-09). «SID86». Newsgroup: comp.os.cpm. Retrieved 2018-04-08.
[…] Since the DR-DOS 7.03 DEBUG is still based on the old SID86.EXE, I suggest to run DEBUG 1.51 and enter the extended help system with ?? from the debug prompt. This will give you eight screens full of syntax and feature help. Some of these features were also supported by older issues. […]
- ^ a b Paul, Matthias R.; Frinke, Axel C. (2006-01-16). FreeKEYB — Advanced international DOS keyboard and console driver (User Manual) (v7 preliminary ed.).
- ^ CCI Multiuser DOS 7.22 GOLD Online Documentation. Concurrent Controls, Inc. (CCI). 1997-02-10. HELP.HLP. (NB. The symbolic instruction debugger SID86 provides a short help screen on
?and comprehensive help on??.) - ^ Paul, Matthias R. (1997-05-24) [1991]. «DRDOSTIP.TXT – Tips und Tricks für DR DOS 3.41 — 5.0». MPDOSTIP (in German) (47 ed.). Archived from the original on 2016-11-07. Retrieved 2016-11-07.
- ^ «The Open Group Base Specifications Issue 7, Chapter 12.1 Utility Argument Syntax». The Open Group. 2008. Archived from the original on 2013-04-30. Retrieved 2013-04-07.
man-pages(7)– Linux Conventions and Miscellany Manual (NB. Conventions for describing commands on Unix-like operating systems.) - ^ «Command shell overview». Windows Server 2003 Product Help. Microsoft. 2005-01-21. Archived from the original on 2012-07-12. Retrieved 2013-04-07.
- ^ «Command-Line Syntax Key». Windows Server 2008 R2 TechNet Library. Microsoft. 2010-01-25. Archived from the original on 2013-05-04. Retrieved 2013-04-07.
- ^ Kernighan, Brian W.; Pike, Rob (1984). The UNIX Programming Environment. Englewood Cliffs: Prentice-Hall. ISBN 0-13-937699-2.
- ^ Pouzin, Louis. «The Origin of the Shell». Multicians.org. Archived from the original on 2017-12-21. Retrieved 2013-09-22.
- ^ «Remembering Windows 95’s launch 15 years later». 2010-08-24. Archived from the original on 2015-02-18. Retrieved 2015-02-18.
- ^ «A history of Windows». windows.microsoft.com. Archived from the original on 2015-03-01.
- ^ «Windows POSIX shell compatibility». 2013-02-22. Archived from the original on 2017-07-03. Retrieved 2017-08-26.
- ^ «master — platform/external/mksh — Git at Google». android.googlesource.com. Archived from the original on 2016-01-21. Retrieved 2018-03-18.
- ^ «Android adb shell — ash or ksh?». stackoverflow.com. Archived from the original on 2017-07-02. Retrieved 2018-03-14.
- ^ «Android sh source». GitHub. Archived from the original on 2012-12-17.
- ^ «Android toolbox source». GitHub.
- ^ openharmony/third_party_toybox, OpenHarmony, 2021-10-14, retrieved 2024-07-07
- ^ «调测 — Shell介绍 — 《华为鸿蒙操作系统(OpenHarmony) v1.0 开发者文档》 — 书栈网 · BookStack». www.bookstack.cn. Retrieved 2024-07-07.
- ^ «Configuration Fundamentals Configuration Guide, Cisco IOS Release 15M&T». Cisco. 2013-10-30. Using the Command-Line Interface. Archived from the original on 2016-11-18. Retrieved 2016-11-28.
The Cisco IOS command-line interface (CLI) is the primary user interface…
- ^ «Command-Line Interface Overview». www.juniper.net. Archived from the original on 2003-09-08. Retrieved 2018-03-14.
- ^ «Google strange goodness». Archived from the original on 2014-03-04. Retrieved 2014-02-27.
- ^ «jQuery Terminal Emulator». Archived from the original on 2021-04-20. Retrieved 2021-04-20.
- ^ «DuckDuckGo TTY». Archived from the original on 2021-05-07. Retrieved 2021-04-20.
- The Roots of DOS David Hunter, Softalk for the IBM Personal Computer March 1983. Archived at Patersontech.com since 2000.
- Command-Line Reference: Microsoft TechNet Database «Command-Line Reference»
What is Windows CLI?
Windows CLI is a secure MCP server designed for controlled command-line interactions on Windows systems, allowing access to PowerShell, CMD, Git Bash, and remote systems via SSH.
How to use Windows CLI?
To use Windows CLI, configure it by creating a JSON configuration file specifying security controls, then execute commands via MCP clients like Claude Desktop using npx @simonb97/server-win-cli.
Key features of Windows CLI?
- Multi-shell support: Execute commands in PowerShell, CMD, and Git Bash.
- SSH support: Control remote systems via SSH.
- Robust security controls: Includes command and SSH command blocking, path restrictions, command logging, and smart argument validation.
Use cases of Windows CLI?
- Securely executing scripts in various command-line environments.
- Managing remote servers through SSH seamlessly.
- Logging and auditing command history for security compliance.
FAQ from Windows CLI?
- Is Windows CLI safe to use?
Yes, Windows CLI includes various security controls to restrict command execution and access paths to ensure safety.
- Can I customize the settings?
Absolutely! You can specify custom rules, shell-specific settings, and SSH connection profiles in the configuration file.
- What happens if I don’t configure it?
The server will run with a default restrictive configuration to protect your system.
