Man command for linux

Что такое man

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

Поэтому разработчики придумали специальную систему справки, в которой вы можете найти информацию о любой команде. Большинство команд содержат в своих пакетах страницы справки, которые добавляются в общую базу данных во время установки. Как вы уже поняли, в этой статье мы разберемся что такое man и как пользоваться этой утилитой.

Что такое man?

Команда man позволяет получить доступ к общей базе справки по команде, функции или программе. Обычно для просмотра справки программе надо передать название команды или другого объекта в системе. Синтаксис у неё такой:

$ man раздел название_страницы

Обычно название страницы совпадает с именем команды или названием программы. Вся справка разделена на несколько разделов. По умолчанию страницы справки выводятся из всех разделов, но вы можете выводить страницы справки из определённого раздела. Для этого достаточно передать номер раздела команде. Вот список основных разделов:

  • 1 — команды оболочки или программы;
  • 2 — системные вызовы;
  • 3 — функции библиотек;
  • 4 — файлы из каталога /dev;
  • 5 — форматы файлов;
  • 6 — игры;
  • 7 — разное;
  • 8 — команды администрирования системы;
  • 9 — процедуры ядра.

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

Для команды ls справка вызывается так:

Каждая страница справки разделена на несколько секций. Вы можете видеть их на снимках экрана выше. Это:

  • NAME — имя программы или команды, а также краткое её описание;
  • SYNOPSIS — синтаксис команды и порядок передачи в неё опций;
  • DESCRIPTION — более подробное описание команды;
  • CONFIGURATION — настройки программы;
  • OPTIONS — опции команды;
  • EXAMPLE — примеры использования;
  • AUTHORS — авторы программы.

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

Для просмотра информации и управлением страницей справки используются такие горячие клавиши:

  • стрелка вверх/вниз — прокрутка информации вверх или вниз;
  • e или j — переместиться на одну строку вверх;
  • y или h — переместиться на одну строку вниз;
  • z — переместиться на одно окно вниз;
  • w — переместиться на одно окно вверх;
  • d — переместиться на пол окна вниз;
  • u — переместиться на пол окна вверх;
  • / — поиск вхождений указанных после символов вперед;
  • ? — то же самое, что и предыдущее, только поиск назад;
  • n — в режиме поиска отображение следующего вхождения;
  • N — в режиме поиска отображение предыдущего вхождения.
Читайте также:  Better performance on linux

С перемещением по странице, скорее всего, всё понятно. Для того чтобы искать какое-либо слово на странице нажмите клавишу / и начните набирать слово, которое надо искать. Оно будет отображаться внизу окна:

Затем нажмите Enter и программа подсветит все вхождения этого слова в текст. Для поиска следующего вхождения нажимайте n:

Этих клавиш вам полностью хватит чтобы пользоваться справкой. Для вывода информации используется утилита less, поэтому если вам нужно больше горячих клавиш, смотрите соответствующую статью.

При запуске утилиты можно использовать несколько опций, давайте рассмотрим эти опции. Их не так уж много и самые интересные из них только несколько. Опция -f позволяет посмотреть краткое описание справочной страницы. Например:

С помощью опции -k можно выполнять поиск по кратким описаниям справочных страниц. Например, давайте найдём все страницы, в описаниях которых есть слово printf:

Опция -K позволяет выполнять поиск по самим справочным страницам. Поиск выполняется методом перебора, поэтому занимает некоторое время:

Команда будет открывать найденные страницы по очереди. Для выхода нажмите Ctrl+C. Опция -L позволяет вручную задать язык, на котором будет отображена страница. Например для вывода информации про man на английском выполните:

А чтобы отобразить man на русском Linux надо передать этой опции значение ru_RU:

Однако для того чтобы это работало нужно чтобы в системе были установлены пакеты локализации для русского языка.

Выводы

Если вам нужны другие опции, вы можете найти их в справочной странице для команды man. Перечисленного в этой статье по моему мнению будет вполне достаточно для полноценного просмотра справки по нужным вам программам. Если вы хотите разобраться с Linux вам обязательно придется научиться пользоваться двумя вещами. Первая из них — это Google, а вторая — справка man. Удачи в изучении Linux!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

man Command in Linux with Examples

The man command is a built-in manual for using Linux commands. It allows users to view the reference manuals of a command or utility run in the terminal. The man page (short for manual page) includes a command description, applicable options, flags, examples, and other informative sections.

In this tutorial, you will learn to use the man command in Linux.

How to use the man command in Linux.

  • A machine running Linux
  • Access to the command line
  • An account with root privileges

Linux man Command Syntax

The basic man command syntax is:

man [option] [section number] [command name]
  • option – the search result output.
  • section number – the section in which to look for the man page.
  • command name – the name of the command which man page you want to see.
Читайте также:  Kaspersky шлюз соединений linux

By default, man looks in all the available sections of the manual and shows the first match (even if the page exists in several sections). Providing a section number instructs the man command to look in a specific section.

There are nine sections of the manual:

1. General commands: Commands used in the terminal.

2. System calls: Functions the kernel provides.

3. Library functions: Functions in program libraries.

4. Special files: Usually devices found in /dev and related drivers.

5. File formats and conventions: File formats like etc/passwd.

6. Games: Descriptions of commands that display database quotes.

7. Miscellaneous: Various descriptions, including macro packages and conventions, boot parameters, and others.

8. System administration commands: Commands mostly reserved for root.

9. Kernel Routines: Information about internal kernel operations.

How to Use man in Linux

In the terminal window, type man followed by the Linux command name which man page you want to see.

The output is lengthy. Use the mouse scroll wheel, the up and down arrow keys, or the PgDn and PgUp keys to navigate through it.

After running the man command, press H to see the help section and a table of possible keystrokes for navigating the output.

To exit, press Q.

The output of the command displays the available man page headings for the specified command.

The list of possible headings includes:

  • Name: The name of the command.
  • Synopsis: The command’s syntax.
  • Configuration: Configuration details for a device.
  • Description: A description of the command.
  • Examples: Several examples demonstrating the use of the command.
  • Defaults: The default functions of the command and how they can be overridden.
  • Options: A list of options and flags that the command accepts.
  • Exit Status: A list of possible exit status values for the command.
  • Environment: A list and description of environment variables that affect the command.
  • Files: A list of files used by the command.
  • See also: Commands related to the described topic.
  • Authors: The people who wrote or maintain the command.
  • History: Command development history.
  • Notes: Various notes, including permissions required, dependencies, etc.
  • Bugs: Any known issues in this program version.

Note: Pages may contain more or fewer headings depending on the man page contents.

Look for man Pages

The -f option displays all man pages that match the specified command name and states the sections in which the given command is present.

Look for man pages in Linux.

The output is a list of results that match the search criteria. With multiple matches, the number next to the search result indicates the section.

Display man Pages From Specific Sections

To display the page from a specific section of a manual, use the syntax:

man [section number] [command name]

See a man page from a specific section.

The output shows only the page from section 3 of the manual.

Читайте также:  Linux подняться уровень выше

Display man Pages in a Browser

Man pages are long and sometimes difficult to scroll through to find the information you need. The man command allows users to display man pages in a browser to find information easily.

To do so, follow these steps:

1. Make sure the groff package is installed. Run:

sudo apt-get install groff

2. Before calling the man command, select a default browser. Run:

To use a different browser, replace firefox with google-chrome , chromium-browser , or any other browser.

3. Use the -H option to read the man page in a browser of your choice:

Man pages can be read in browsers using the -H option.

The -H option instructs groff to produce an HTML output and displays that output in a browser.

Display man Pages and Print Short Descriptions

The -f option allows users to look up the man pages and prints out short descriptions of the specified command in the terminal. The syntax is:

See a short man page description.

Display All man Pages

The -a attribute allows users to display all available intro manual pages contained in each section, one at a time.

Display all man pages using the -a option.

Quit between successive displays or skip through them using Ctrl+C or Ctrl+D, respectively.

Search by Considering Input as a Regular Expression

The -k option allows users to search the short command descriptions and manual page names for a specified keyword as a regular expression. The output shows any available matches.

Conduct a search in man considering input as a regular expression.

Display Location of man Pages

The -w attribute shows the location of the manual page of the specified command. Adding the -a option prints out the locations of all files matching the keyword.

See the location of man pages using the -w option.

In this example, we used the -a option to see the locations of all associated man pages.

Additionally, using the -W option displays the location of the preformatted cat file. With the -a option, it prints out the locations of all preformatted cat files matching the keyword.

Enable Case-Sensitivity

To search for manual pages using case-sensitivity, use the -I option. The syntax is:

The man default setting is to ignore case when looking up manual pages. To go back to default settings and ignore case, use the -i option.

Search for man pages with case sensitivity enabled.

You now know how to use the man command in Linux. Use the command to see user manuals for Linux commands, search for a specific keyword, or see all the entries in the manual.

To learn how can you search all man pages using known details as a search term, make sure to read our article apropos Linux command.

For more uses, refer to our article and find out how can man command review the complete manual for Expect.

Источник

Оцените статью
Adblock
detector