Cli что это в программировании
Перейти к содержимому

Cli что это в программировании

  • автор:

How to Use the Command Line Interface – for Beginners

Maybell Obadoni

Maybell Obadoni

How to Use the Command Line Interface – for Beginners

There’s a lot to learn when you’re getting into tech. But fortunately there are some skills that you can use across different programming languages, operating systems, and tools.

And knowing how to use the command line interface (also known as the command prompt or terminal, depending on your operating system) is one of those skills.

Whether you’re doing Web development, Game Development, Application Development, Cloud Engineering, DevOps, or many other disciplines in tech, you’ll likely use the command line quite often.

History of the Command Line

In the early days of computers, developers used MS-DOS to navigate around the computer system.

image-390

Disk Operating System (DOS) is a kind of operating system that uses commands (words) to interact with the computer.

The DOS didn’t use mouse pointers, icons, or any graphics, so users were stuck with using text-commands to operate the computer system.

For instance, to go to a particular folder, you’d type:

Cd <name of folder>

The command line interface (or CLI for short) is similar to DOS in that it uses commands to perform various operations, like creating files, creating folders, installing programs, and what have you.

The advancement of technology over the years brought about the popular GUI (Graphical User Interface) and made Operating Systems less stressful to use.

Although developers (and non-technical users) often use the GUI these days, sometimes working directly from the CLI is useful or necessary, irrespective of your stack.

What is the CLI? Is it a Programming Language?

A portrait of a girl with a cute expression.

Photo by Angshu Purkait / Unsplash

If you’re new to software development, it’s easy to get carried away with the various terminology you’ll need to learn. Worry less, you are not doing a spelling bee competition. Rather, you are meant to learn what these terms refer to, how they actually work, and how you can use them.

One of the terms you’ll hear quite often is the Command Line Interface (also referred to as Command Prompt or Terminal).

The Command Line Interface (CLI) is an editing environment that is text-based. It uses specified text (known as commands) to interact with the computer and perform numerous operations, including installing and working with programs.

Every operating system comes with an inbuilt command prompt. Some application packages such as Nodejs, Anaconda, Git, and so on also come with their own command prompt.

The same thing goes for Cloud Providers such as AWS, GCP, Azure. Although the CLI bears different names across different platforms or packages, its purpose remains the same: to let you interact freely with the software package or the computer system using text-based instructions known as commands.

So, the CLI is a tool, not a programming language.

A basic knowledge of CLI will help you along your tech journey, especially if you are into Software Development. In fact, you can completely build a program and run it right from the CLI.

This article will:

  • Explain how the CLI Works
  • Help you locate your CLI according to your OS
  • Show you how to perform basic operations using the CLI
  • Help you differentiate between the CLI and GUI

How the CLI Works

As briefly discussed earlier, the CLI uses text-based instructions to perform operations. These commands have specific syntax you need to follow and certain text must be written on the same line – otherwise it’ll throw an error message.

In the case of CLI in application packages, the commands may be relative to the package in question. But all CLIs follow the same rule of being semantic and on the same line.

To use your CLI:

  • Locate the CLI in your PC
  • Open it
  • Type in your desired commands
  • Press the enter key

Later in the tutorial, we’ll execute some commands using the CLI so you can better understand how it works.

The Command Line in Different Operating Systems

Every Operating System comes with its default Command Line Interface, though you can choose to install a more advanced CLI depending on your needs.

Some Operating Systems and their respective CLIs are listed below:

  • Windows: Command Prompt
  • Linux: Linux Bash Shell
  • MacOs: Mac Terminal
  • Google Cloud Platform: PowerShell, Cloud shell
  • Amazon Web Services: AWS Command Prompt
  • Microsoft Azure: Azure CLI bash

I currently use Windows OS and Windows Command Prompt, but I’ll also show you how you can locate your own Terminal or Command Prompt based on popular Operating systems.

How to Locate your CLI

In Windows

You can access the command prompt in Windows OS using the program directory or using shortcut keys.

Using the program directory, go to your search bar (next to the Windows icon) and type cmd. This will pop up a list of all the command prompts available on your machine, including the default windows cmd. You can now select the one you wish.

Using a keyboard shortcut, press Windows + R on your keyboard and type in cmd on the dialog box that pops up.

CMD-1

A picture showing the run terminal

In MacOS

As in the case of Windows, you can also open the CLI in a Mac OS using the program directory or a keyboard shortcut.

To use the program directory, locate the launchpad and type in Terminal. This will bring it up.

To use the keyboard shortcut, type the combination of the cmd + space bar keys.

Here’s how to locate MacOs Terminal and create a file in a directory:

How to Perform Basic Operations Using the CLI

Back in Mathematics class, it was quite easy to memorize formulas and solve equations using those memorized formulas. But knowing when to apply those equations in real life scenarios was – and often continues to be – difficult for many students.

Knowing where your CLI is located and how it works is a good step in the right direction. But let me show you how to get started with the CLI by practicing simple operations right from your Command Prompt.

How to navigate through your PC with the CLI

Navigating through your PC simply means moving from one folder or file to another. If you don’t want to use your mouse to direct your cursor, you can move around your PC using the CLI.

For instance in Windows, if you want to open the desktop, take the following steps:

  1. Open the CLI (CMD) as explained earlier
  2. Next, type in cd Desktop on the command prompt which will take you to your desktop

Keep in mind that this command is for Windows OS (for Mac, for example, it’ll be slightly different).

Here’s what you’ll see:

CMD-2

How to create a folder using the CLI

You may know the usual method of right-clicking on your screen and selecting the «New folder» option on the drop-down menu. But there’s a way of creating a new folder using the CLI.

  1. First, open your CLI
  2. Navigate to the folder or location where you want to create the new folder
  3. Enter mkdir <name_ of _new_folder>
  4. Press Enter
  5. You can now enter the folder by typing cd <name_ of _new_folder>

How to install a package using the CLI

Installing a software package or application using the CLI depends on the package in question.

Packages like Node.js (a development package for BackEnd Development) require that you install the Node Package Manager (npm). This package manager is what you’ll use to install and run Node and other similar packages.

Some commands for installing software packages via the CLI include:

  1. Install <name of package>
  2. run <name of package

For instance to install a new instance of a React app:

Open the terminal

locate your local environment by typing:

  • Create a directory for the app by typing:

cd Desktop mkdir my_directory

  • create the react-app right in the directory by using the command:

npx create-react-app my-app

cmd9

A terminal showing the commands for installing create-react-app using Windows Command Prompt

Differences Between the CLI and GUI

BEGINNERS--HACK-ON-USING-CLI--3-

GUI vs CLI image

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

As we’ve discussed, the CLI uses commands to generally interact with the computer.

On the other hand, the Graphical User Interface (GUI) is a method of interacting with the computer using icons, menus, mouse clicks, and pointers.

An Operating System that is GUI-based allows users to freely operate the computer by clicking, dragging, dropping, and other visual methods of interacting with the computer.

Unlike the GUI, the CLI uses less RAM space and interacts with the operating system directly.

To use the GUI, no programming knowledge is required. But to use the CLI, you need to have a certain amount of knowledge of programming and command operations.

Conclusion

As you begin or advance in your tech journey, you’d need to install a lot of programs that are foreign to your Local Machine. Such programs may not have GUI installation methods and may require you to run a line of code or more on your CLI. At such a point, knowledge of using the CLI comes in handy.

There’s a general notion that the CLI is difficult to use – and it does take some getting used to. But once you get acquainted with the operations of CLI you’ll find it much easier to manage.

What Is CLI?

CLI is a powerful program, but its use CLI hasn’t always been well-received. Beginners are reluctant to use it, thinking that it is only for advanced users. But, that is not true.

In this article, you will learn everything you need to know about CLI.

What Is CLI?

CLI stands for command line interface. It is a program that allows users to type text commands instructing the computer to do specific tasks.

The Roots of CLI

In the 1960s, CLI was used intensively.

Back then, people had only a keyboard as an input device and the computer screen could only display text information. The operating systems like MS-DOS used the CLI as the standard user interface.

Windows Command Line Interface

Basically, users had to type a command on the CLI to perform tasks, as this was the only way to communicate with the computer.

After typing a command, the result users got would be either text information or specific action performed by the computer. That being said, typing the right command is the key.

If users type the wrong command, chances are they’ll end up deleting the wrong files or accidentally closing the program before saving their work. This is what people consider as the main drawback of using CLI.

Then, after years of only using a keyboard and risking to misuse the command line, the mouse was invented.

The invention of a mouse marked beginning of the point-and-click method as a new way to interact with the computer.

This method is much safer for average users, thus drove them away from CLI. But, later on, we will discuss that using CLI is better. Stay with us.

Apart from that, operating systems started to develop an attractive way of computing, using GUI (Graphical User Interaction). GUI itself was phenomenal because of the use of buttons and menus to represent specific commands. This approach has been proven to be very intuitive.

Today, GUI has become a common way of computing. However, most operating systems still offer a combination of CLI and GUI. For example, Mac users can either type “cal” in Terminal or click on a Calendar application to get the same results.

Displaying Calendar in TerminalShell – The Foundation Behind CLI

If we dive from CLI into the deeper part of an operating system, we will find the shell.

Shell is a user interface responsible for processing all commands typed on CLI. It reads and interprets the commands and instructs the operating system to perform tasks as requested.

In other words, a shell is a user interface that manages CLI and acts as the man-in-the-middle, connecting users with the operating system.

In practice, there are many things that shell can process, such as:

  • Working with files and directories
  • Opening and closing a program
  • Managing computer processes
  • Performing repetitive tasks

Among many types of shell, the most popular ones are Windows shell (for Windows) and bash (for Linux and MacOS).

Windows Shell

The default shell in Windows is CMD.exe or the Command Prompt. In fact, Microsoft has used the Command Prompt since the old days, where MS-DOS was the main operating system.

To open the Command Prompt, you can click Start -> All Programs -> Accessories -> Command Prompt. Or, you can simply press Windows+R, then type CMD, and press enter.

Depending on what you need, type in either a single command or a combination. You can also type commands that run within a sequence (one command is executed after another).

The Command Prompt is so robust that it can manage many things within the Windows operating system:

  • Changing directories, listing directories, content, etc
  • Handling networking like displaying IP networks settings
  • Managing files like renaming, moving, etc
  • Managing media like formatting and renaming volumes

Now, let’s learn how to use some syntax in the command prompt:

    Changing directory
    To navigate to a specific directory or folder in the command prompt, use CD[path]. Make sure you add space before the intended path. For example:

Bash stands for Bourne Again SHell and was developed by the Free Software Foundation.

Bash is a type of shell used in MacOS and many Linux distributions. However, you can also install bash Linux on Windows 10.

In Linux, Bash shell is one of many shells the Linux users can use. The other types are Tchs shell, Ksh shell, and Zsh shell.

In most Linux distributions, the shell is located under the Utilities menu. If you use Gnome desktop, the name is Terminal, but if you use KDE, the name is Konsole.

Meanwhile, in MacOS, the program is Terminal.app. To run this program, go to Application -> Utilities -> Terminal. Or, you can simply type terminal using Spotlight search.

Once the terminal’s opened, you can start typing a command. Basically, most commands consist of: the command itself, the argument, and the option.

While the command contains the instruction we want to perform, the argument tells where the command should operate and the option requests the modification of the output.

Now it’s time to learn how to use the shell.

To begin with, you need to know the syntax to deal with the shell. This is also known as shell scripting – ways of using the script in CLI to run certain tasks.

While there are many commands you can use with CLI, they all fall into two categories:

  • The commands that handle the processes
  • The commands that handle the files

To understand the command syntax in MacOS, let’s learn from these examples:

    List all files in a folder
    To know what files under a specific folder, use ls.
    The default command will exclude the hidden files. To show all files, you can add -a. For example:

Listing All Files in a Folder Using CLI

Change Directory Using MacOS Terminal

Renaming a File Using MacOS Terminal

Deleting a File Using MacOS Terminal

Again, typing the right command is important. That means you should pay attention to each character you use, including space. Not only that, make sure you type the correct case.

If for certain reasons you want to stop the ongoing process on the Command Prompt or Bash, simply hit Control+C.

Why Would You Use CLI over GUI?

As previously mentioned, the GUI was developed within the operating system as soon as the mouse became a new input device to operate the computer.

We should admit that GUI is visually attractive and easily understood. But, for some tasks which are vital, CLI is way more powerful.

Here, we would like to pick some points why you would use CLI over GUI. However, we leave it to you to choose depending on your type of work.

  1. Less Resource
    It is not a secret that the text-based program needs very little resources of your computer. This means that with CLI you can do similar tasks with minimum resources.
  2. High Precision
    You can use a specific command to target specific destinations with ease. As long as you don’t type the wrong command, it will work like a charm. Once you learn the basics, writing syntax is not as hard as you might think.
  3. Repetitive Tasks Friendly
    GUI has developed well over the years. But, the operating system may not give you all the menus and buttons to perform all tasks. One of the reasons is safety. This leaves you overwhelmed if you have to do repetitive tasks. For example, when you have to handle hundreds of files within a folder, CLI enables you to use a single command to do automate the repetition easily.
  4. Powerful
    Most operating systems today prevent you from messing up the system’s core process. Windows has system protection and MacOS has SIP (System Integrity Protection). You won’t be able to perform certain tasks which are system protected. However, with CLI, you will have full control over your system.

To give you an illustration, there is a method called PSD to HTML in website development.

In PSD to HTML, the process starts with making a mockup in Photoshop. The Photoshop Document (PSD) is then converted to HTML.

Converting PSD to HTML involves hand-coded work. The web developer will make sure that the code used in the conversion is clean. This is important to pass W3C compliance.

W3C compliance will ensure that the website has good code to make it compatible with all browsers.

So, understanding the code is vital to understand the core process.

The same thing goes for CLI in the operating system. While the GUI may seem appealing, CLI is light, powerful and straightforward.

Conclusion

Despite a long debate that CLI is only for the experts, you have now learned it is for average users as well.

The fact that most operating system still provides CLI along with GUI proves that CLI is crucial. Also, using CLI gives more positive points than GUI because:

  • It needs fewer resources
  • It ensures high precision
  • It handles repetitive task easily
  • It is powerful

Now, let’s get the job done using CLI!

Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.

Как пользоваться CLI для автоматизации рутинных процессов

Как пользоваться CLI для автоматизации рутинных процессов главное изображение

Пятьдесят лет назад у программ не было удобных пользовательских интерфейсов: единственным средством ввода была клавиатура, приложения вызывались путем написания их имен, а вывод был текстовым.

Разработчикам приходилось проявлять изобретательность, чтобы сделать программы более гибкими. Так появился интерфейс командной строки (или пользовательский интерфейс командной строки — CLI). Его определение звучит как «параметрическая компьютерная программа, которая получает входные данные (параметры и опции) через консольный интерфейс или скрипт».

Следующим шагом было появление графического пользовательского интерфейса (GUI), который вытеснил CLI в узкую область системного администрирования, разработки и поклонников Unix.

Хотя CLI далек от былой популярности, среди разработчиков он переживает период возрождения. Многие приложения (например, VS Code и Spotify) интегрировали CLI в свои пользовательские интерфейсы, а языки программирования (например, Node.js и Golang) используют его для упрощения процесса разработки.

Интерфейс командной строки полезен, когда нужно передавать сценарии или команды с одинаковым набором параметров, а также для автоматизации определенных последовательностей действий.

Преимущества CLI

Инструменты интерфейса командной строки можно рассматривать как набор сценариев автоматизации, объединенных удобным API. Речь идет обо всех преимуществах автоматизации рутинных действий (повышение производительности, снижение количества ошибок и других) в купе с гибкостью.

Вероятно, вы подумали, что графический интерфейс лучше подходит для этих целей и выглядит удобнее. Однако он потребляет больше ресурсов при запуске и его сложно масштабировать. Кроме того, разработка графического интерфейса занимает больше времени и стоит дороже, чем CLI.

Преимущества CLI для бизнеса можно описать так:

  • Использование интерфейса командной строки ускоряет время вывода продукта на рынок
  • Снижает затраты по сравнению с использованием пользовательского интерфейса
  • Снижает затраты на онбординг новых сотрудников.

Подробно эти пункты раскрыты в исследовании IBM и Forbes, а также в отчете McKinsey.

Как создать собственный CLI

Можно создать собственный интерфейс командной строки с нуля, но гораздо удобнее использовать фреймворки: они существуют для Python, Javascript, Golang и многих других языков программирования.

Для этой статьи я использовал JS-фреймворк с открытым исходным кодом commander.js, который работает на Node.js.

Прежде чем перейти к коду, рассмотрим некоторые особенности commander.js:

  • Команды в этом фреймворке похожи на исполняемые файлы. Это программы, которым задаются параметры и аргументы
  • Аргумент — то, что передается команде для обработки
  • Параметры — то, что изменяет поведение команды. Они могут быть заданы в короткой (например, -h ) или длинной ( —help ) формах.

Перейдем к коду. Начнем с простого примера, который можно использовать в каждом проекте: вывода «Hello, World!». Создадим файл с именем my.js и добавим в него следующий код:

Эта программа вызывается так:

Теперь сделаем так, чтобы программа могла учитывать некоторые параметры (аргументы). Например, приветствовать людей по именам:

Из примера выше видно, что программа принимает количество имен, отличное от нуля, в качестве аргументов. Для этого используется метод arguments(args) , а в методе action(Function) имена можно обрабатывать так, как мы хотим. Аргументы передаются вместе с командой вызова и указываются через пробелы:

В таком виде программа уже выглядит интереснее. Теперь реализуем одно из главных преимуществ CLI — возможность работать с несколькими командами одновременно:

Теперь создадим другой файл, следуя правилу имен: файл точки входа и имя команды через дефис. В этом примере файл точки входа my.js, значит чтобы вызвать команду hello , мне понадобится файл my-hello.js.

Попробуем вызвать команду hello передав её вместе с именами:

Теперь проверим, как CLI может менять функциональность, передавая параметры. Чтобы сделать это, просто вызовем метод option(opts, description) :

В результате получаем следующее:

Заключение

Мы только что создали очень упрощенный, но рабочий инструмент, используя возможности интерфейса командной строки. Посмотреть результат можно здесь. Чтобы развернуть его, можно отправить код в npm, локально связать с npm-пакетами или создать имя для команды оболочки.

Хотя именно этот инструмент бесполезен в практических целях, в документации commander.js есть описание инструментов, которые принесут реальную пользу.

Никогда не останавливайтесь: В программировании говорят, что нужно постоянно учиться даже для того, чтобы просто находиться на месте. Развивайтесь с нами — на Хекслете есть сотни курсов по разработке на разных языках и технологиях

Интерфейс командной строки

Что такое командная строка и какие команды можно отдавать компьютеру.

Время чтения: 9 мин

  1. Кратко
  2. Как понять
  3. На практике
    1. Игорь Коровченко советует

    Обновлено 21 декабря 2021

    Кратко

    Скопировать ссылку «Кратко» Скопировано

    Интерфейс командной строки (терминал, консоль, Command line interface, CLI) позволяет человеку взаимодействовать с компьютером с помощью текстовых команд заданного формата. Эти команды указывают, что и в какой последовательности делать. В ответ компьютер может выводить на экран информацию о результатах работы той или иной команды.

    Как понять

    Скопировать ссылку «Как понять» Скопировано

    Взаимодействие с компьютером через текст появилось практически на самых первых этапах развития компьютерной техники. Такой интерфейс выглядит хоть и скучновато, но является очень мощным инструментом. В Unix-подобных системах CLI помогает пользователю настраивать операционную систему и службы в них, взаимодействовать с файлами, внешними устройствами, подключёнными к компьютеру сетями, Интернетом. В Unix-подобных системах любые данные, устройство или программа в абстракции операционной системы представляется в виде файла, именно поэтому терминал в них обладает такой мощью. В других операционных системах также существуют интерфейсы командной строки, но их функциональность ограничена, как правило, сервисными функциями для управления операционной системой.

    Запустить терминал можно как обычную программу в вашей операционной системе. На компьютерах Mac эта программа так и называется «Терминал». В операционных системах из семейства Linux терминал установлен по умолчанию и доступен не только в списке программ, но и по сочетанию клавиш Ctrl Alt T . В Windows программа для работы с консолью самой операционной системы установлена по умолчанию, находится в меню Пуск → Все программы → Стандартные и называется «Командная строка». Однако разработчикам больше подойдёт «PowerShell», ну а для полноценной работы лучше использовать WSL (Windows Subsystem for Linux) первой или второй версии. Эта программа позволяет использовать всю мощь командной строки Unix-подобных систем, её можно скачать из магазина приложений Microsoft Store. Процесс установки достаточно подробно описан в официальной документации.

    В «Терминале» текстовый интерфейс для пользователя выглядит следующим образом:

    Структура интерфейса командной строки

    Приглашение командной строки всегда отображается, когда операционная система готова выполнить следующую команду пользователя. В приглашение командной строки можно вывести довольно много разной информации. Обычно в приглашение помещается имя компьютера, терминалом которого вы пользуетесь, и имя текущего пользователя, например: UserName@MyComputer $ . Часто, кроме этой информации, может быть явным образом указана текущая директория, например: UserName @ MyComputer in / etc $ . Можно изменить цвет текста или поместить дату и время. В приглашении может хранится информация о текущей ветке в системе контроля версий, например: UserName @ MyComputer in / etc $ on git : main . Бывают и обратные ситуации, когда удобно использовать короткое приглашение, чтобы не загромождать интерфейс, например: > или $ .

    Для удобства читателя примеры ниже не содержат приглашения командной строки, однако, на практике терминал будет его выводить в том или ином виде.

    В современных операционных системах можно использовать одновременно несколько терминалов, в каждом из которых могут выполняться свои команды. Если говорить в общем, то к CLI можно подключиться и с другого компьютера через сеть.

    Каждая команда уникальна, иначе операционная система не сможет понять, что ей нужно делать. Команда — это всегда специальное слово, которое запускает отдельное приложение: пользовательскую программу, консольную утилиту, службу и тому подобное. Например, можно узнать текущую дату командой:

    Нажмите клавишу Enter , чтобы выполнить команду. Все, что идёт после команды, называется аргументами командной строки. Часть специальных аргументов, которые настраивают работу команды, принято называть ключами (флагами, параметрами). С помощью ключей пользователь может указать, в каком режиме будет работать команда, задать значения по умолчанию и прочее. Ключи, состоящие из нескольких символов, принято обозначать двумя дефисами в начале. Например, для большинства команд можно посмотреть короткую справку с помощью ключа — — help . Часто используемые длинные ключи также имеют короткий аналог (псевдоним, alias) из одного символа, например -h для той же справки. Короткие ключи, как правило, можно указывать вместе, поставив перед ними дефис:

    • cal — вывод календаря для текущего месяца с подсвеченной текущей датой;
    • cal — h — не подсвечивать текущую дату;
    • cal — hj — не подсвечивать текущую дату и заменить числа месяца на номер дня в году;
    • cal — hy — не подсвечивать текущую дату и вывести календарь для всего текущего года.

    Символ # в начале строки используется для однострочного комментария.

    Вывести список всех терминалов, которые работают сейчас в системе с указанием пользователя, от имени которого они запущены и времени запуска, можно так:

    Для большинства стандартных команд существует подробное описание ключей и аргументов. Это описание доступно по команде man (от “manual”). Вы можете посмотреть краткую справку для этой команды так:

    На следующей строке вы видите текущую версию программы, затем идёт описание формата команды. Квадратные скобки указывают на аргумент, который можно использовать, но он не является обязательным. Без квадратных скобок указываются аргументы, которые использовать необходимо. Этого синтаксиса, как правило, придерживаются в любой справочной информации для команд текстового интерфейса. Например name обозначает имя команды, справку о которой мы хотим получить. Для получения справки по команде pwd нужно выполнить:

    Терминал перейдёт в специальный режим постраничного просмотра, в котором можно перемещаться клавишами → , ← , ↑ , ↓ , PgUp , PgDown , Home , End . Для того чтобы выйти из этого режима, нажмите клавишу Q . В справке написано, что команда pwd используется для того, чтобы узнать, в какой директории вы сейчас находитесь (рабочая директория). Имя этой команды идёт от аббревиатуры PWD — Present Working Directory. В любом случае вы работаете внутри какой-либо рабочей директории. Среди специальных директорий можно выделить:

    • корневую директорию, которая доступна в /;
    • домашнюю директорию пользователя, доступную в /home/<имя пользователя> или по псевдониму

    В Unix-подобных системах скрытые директории и файлы помечаются точкой в начале.

    Сочетание клавиш Ctrl A позволяет переместиться к началу строки, Ctrl E — к концу. Нажав Ctrl L вы сможете очистить экран, переместив строку приглашения на верх окна. То же самое делает команда clear . Клавиша Tab позволяет использовать автодополнение, например, для имён директорий или файлов. Двойное нажатие позволит посмотреть все доступные варианты. Клавишами ↑ , ↓ можно перемещаться по списку уже выполненных команд, что бывает очень удобно. Чтобы посмотреть полный список команд, которые были вызваны ранее, выполните:

    Количество команд, хранящихся в истории, ограничено настройками терминала. Все настройки обычно сосредоточены в одном файле конфигурации, расположенном в домашней директории пользователя. Подробно о настройке терминала можно почитать, например, в статье «Делаем Linux терминал красивым и удобным».

    Существует довольно много разных терминалов. Самые распространённые для Unix-подобных систем — bash и zsh. Наиболее полный список терминалов можно посмотреть в таблице.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *