Locating commands in linux

Ищем путь до линукс команд, как профессионалы

Один из самых распространённых вопросов от подписчиков — как получить путь к команде Linux, которую только что установили в систему с помощью пакетного менеджера, например, команды apt или DNF. Много новых разработчиков переходит к нам из мира Windows, и для многих это первый опыт использования Linux. Некоторые используют WSL (подсистему Linux в Windows 10), а остальные работают с облачными серверами напрямую по SSH. Рассмотрим ряд распространённых команд, с помощью которых можно отобразить список команд Linux или получить к ним путь.

▍ Что такое команда Linux?

Пользовательский интерфейс Windows по умолчанию графический. Однако у ОС Linux на стороне сервера по умолчанию текстовый интерфейс. Поэтому часто используются такие термины как Bash, оболочка пользователя, консоль, приглашение командной строки, терминал и так далее. Все они относятся к текстовому интерфейсу.

К примеру, в MS Windows-приложения запускаются через кнопку «Пуск». У терминала Linux назначение схожее, но туда вводятся инструкции, известные как команды Linux. Итак, вызываем терминал Linux сочетанием клавиш Ctrl–Alt–T . Затем вводим простую команду — например date , чтобы просмотреть текущую дату и время. Текст команды вводится только строчными буквами. Для запуска команды надо нажать кнопку Enter:


date, pwd, hello и ping — это команды Linux.

▍ Различные типы команд Linux

Команды Linux, которые вводят в терминал, бывают разных типов:

▍ Как определить тип команды Linux

Чтобы просмотреть путь к любой команде Linux, достаточно ввести в терминал команду type . С её же помощью можно узнать тип целевой команды: встроенная команда оболочки, псевдоним, функция или внешняя. Синтаксис следующий:

Например, давайте выясним тип команды pwd:

▍ Что такое переменная $PATH ?

В Linux и Unix-подобных системах переменная PATH содержит перечень путей, по которым хранятся исполняемые программы, например ping, date, vi, docker и так далее. Чтобы просмотреть текущую переменную path, воспользуйтесь командой echo /printf:

Вот что отображается у меня:

Для просмотра всех исполняемых файлов в папке /bin/ , выполните команду ls следующим образом:

▍ Как отобразить информацию о командах

Чтобы получить путь к команде Linux, введите command следующим образом:

▍ Как найти команду Linux

А ещё можно легко получить путь к команде Linux с помощью команды which . Пример:

Чтобы отобразить все возможные совпадающие пути, воспользуйтесь опцией -a :

▍ Получаем путь к команде или man-странице Linux

Чтобы найти двоичный файл, исходный код и man-страницу какой-либо программы или команды на диске, используйте команду whereis в следующем синтаксисе:

Надо, чтобы отображались только двоичные файлы? Есть вот такой вариант:

Ищете только руководства и справочные страницы? Проще простого:

▍ Команды find и locate

Файлы можно также искать по имени файла. К примеру, так будет выглядеть поиск файла, в имени которого содержится слово ‘date’:

Результаты выполнения команды locate:

▍ Вывод справки о командах Linux

С этим нам помогут команды whatis , help , man или info .

Команда whatis :
К каждой команде Linux прилагается man-страница (руководство, описывающее способ применения и синтаксис команды). Кроме того, справка содержит краткое описание команды. Для поиска по названиям man-страниц используется команда whatis. Она отображает описания команд для любых названий, введенных в краткой форме:

Для всех внешних команд используются команды man или info , которые выводят на экран подробное руководство:

Для ключевых слов и встроенных команд Bash используется команда help:

▍ В качестве заключения

Основная проблема, с которой сталкиваются новоиспечённые пользователи Linux — поиск команд. Но благодаря этому доступному руководству вы теперь умеете получать путь к нужным командам и даже выводить справку о них в формате man-страниц. Предположим, вы установили Docker на сервер Ubuntu. Получить путь к этой системе и изучить руководство можно с помощью следующих команд:

Читайте также:  Кнопка сканирования на принтере hp ink tank wireless 415

Если вы работаете с сервером Debian или Ubuntu Linux, вам пригодятся следующие две команды. Отобразить список всех файлов, установленных на сервер пакетом Docker, можно командой dpkg :

Вывести на экран информацию о пакете Docker можно с помощью команды apt :

Надеюсь, новым пользователям и разработчикам Linux эти команды окажутся полезны.

Источник

5 Ways to Find a ‘Binary Command’ Description and Location on File System

With the thousands of commands/programs available in Linux systems, knowing the type and purpose of a given command as well as its location (absolute path) on the system can be a little challenge for newbies.

Knowing a few details of commands/programs not only helps a Linux user master the numerous commands, but it also enables a user understand what operations on the system to use them for, either from the command line or a script.

Therefore, in this article we will explain to you five useful commands for showing a short description and the location of a given command.

To discover new commands on your system look into all the directories in your PATH environmental variable. These directories store all the installed commands/programs on the system.

Once you find an interesting command name, before you proceed to read more about it probably in the man page, try to gather some shallow information about it as follows.

Assuming you have echoed the values of PATH and moved into the directory /usr/local/bin and noticed a new command called fswatch (monitors file modification changes):

Find New Commands in Linux

Now let’s find out the description and location of the fswatch command using following different ways in Linux.

1. whatis Command

whatis is used to display one-line manual page descriptions of the command name (such as fswatch in the command below) you enter as an argument.

If the description is too long some parts are trimmed of by default, use the -l flag to show a complete description.

Linux whatis Command Example

2. apropos Command

apropos searches for the manual page names and descriptions of the keyword (considered a regex, which is the command name) provided.

The -l option enables showing of the compete description.

Linux apropos Command Example

By default, apropos may show an output of all matched lines, as in the example below. You can only match the exact keyword using the -e switch:

Linux apropos Command Show by Keyword

3. type Command

type tells you the full pathname of a given command, additionally, in case the command name entered is not a program that exists as a separate disk file, type also tells you the command classification:

  1. Shell built-in command or
  2. Shell keyword or reserved word or
  3. An alias

Linux type Command Example

When the command is an alias for another command, type shows the command executed when the alias is run. Use the alias command to view all aliases created on your system:

Show All Aliases in Linux

4. which Command

which helps to locate a command, it prints the absolute command path as below:

Find Linux Command Location

Some binaries can be stored in more than one directory under the PATH, use the -a flag to show all matching pathnames.

5. whereis Command

whereis command locates the binary, source, and manual page files for the command name provided as follows:

Linux whereis Command Example

Although the commands above may be vital in finding some quick info about a command/program, opening and reading through its manual page always provides a full documentation, including a list of other related programs:

In this article, we reviewed five simple commands used to display short manual page descriptions and location of a command. You can make a contribution to this post or ask a question via the feedback section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to Use the locate Command in Linux

Home » SysAdmin » How to Use the locate Command in Linux

Читайте также:  Dayz global ban 0x000400f0

The locate command is a Unix utility used for quickly finding files and directories. The command is a more convenient and efficient alternative to the find command, which is more aggressive and takes longer to complete the search.

Opposite to find , the locate command doesn’t search the entire filesystem, but looks through a regularly updated file database in the system. Thus, the search completes much faster.

In this tutorial, you will learn to install and use the locate command in Linux.

  • A system running Linux.
  • An account with administrator privileges.

How to Install locate

Depending on which Linux distribution you are using, the locate package may not be pre-installed.

To check if locate is installed, enter:

If locate is installed on your distribution, the command prints the following output:

For this tutorial, we have used Ubuntu 20.04, which doesn’t come with the locate utility pre-installed. In this case, the output message is:

Install locate on Ubuntu and Debian

Follow the steps below to install locate on Ubuntu or Debian:

1. Update the package repository:

2. Install the locate package by running:

Install locate on CentOS and Fedora

Follow the steps below to install locate on CentOS or Fedora:

1. Update the package repository:

2. Run the following command to install locate :

Note: Installing the mlocate package creates a cron job that runs the updatedb command every 24 hours and updates the database. To manually update the database, use sudo updatedb .

How to Use the locate Command in Linux With Examples

The locate command finds files in Linux using the file name. locate is used for obtaining instantaneous results, and it is an essential utility when speed is a priority.

The command performs the search using a database containing bits of files with the corresponding paths in the system. However, locate doesn’t check for files outside the database, which means it doesn’t report about files created after the most recent database update.

The syntax for the locate command is:

Some useful options are:

Option Description
-A, —all Displays only the entries matching all the specified pattern(s).
-b, —basename Matches only the base name against the specified patterns.
-c, —count Outputs the number of matching entries instead of the file names.
-d, —database [DBPATH] Replaces the default database with [DBPATH] — a colon-separated list of database file names.
-e, —existing Only displays entries for existing files.
-L, —follow Use to check whether files exist if the —existing option is specified. The —follow option omits broken symbolic links.
-i, —ignore-case Ignores pattern case sensitivity.
-p, —ignore-spaces Ignores punctuation and spaces when matching patterns.
-t, —transliterate Uses iconv transliteration to ignore accents and diacritics when matching patterns.
-l, —limit, -n [LIMIT] Use to exit successfully after finding a [LIMIT] number of entries.
-0, —null Separates output entries using the ASCII NUL character instead of printing each entry in a new line.
-S, —statistics Prints the statistics about each read database to standard output instead of searching for files.
-q, —quiet Hides any errors encountered while reading and processing databases.
-r, —regexp [REGEXP] Used for searching a basic regular expression [REGEXP] . Specifying this option doesn’t allow [pattern] arguments.
-w, —wholename Matches only the whole path name against the specified patterns.
-h, —help Displays the help file with a list of all available options.

The following sections list helpful examples of using the locate command.

Search for a File

The simplest way to use the locate command is to input the pattern you want to search for.

For example, search for all files containing the mysql pattern in the filename by running the following command:

The output lists all the absolute paths for the files containing the mysql pattern in the filename.

Format the Output

When the search result is a long list of files, pipe the locate command into less for better readability and easier scrolling.

Navigate the output by pressing the Space bar to move forward, b to reverse, or Q to quit.

Show the Existing Files

While the locate command retrieves results almost instantaneously, the speed comes with a cost. Sometimes deleted files appear in the results because the database that locate reads hasn’t been updated since the files were deleted. Also, new files don’t appear in the results if they were created after the last database update.

Eliminate these shortcomings using the -e option to search the filesystem and include only the existing files in the results.

In the example above, we first deleted a file using rm . Searching for the file with locate shows the deleted file’s location. However, when using the -e option, locate shows no results since the file was removed.

Note: To permanently delete a file and prevent its recovery, use the shred command.

Count the Existing Files

Print the number of matched files instead of the file names and their absolute paths by specifying the -c option.

The output contains only the number of files containing the mysql string in the filename. All other information is suppressed.

Disable Errors While Searching

The -q option instructs locate to suppress any errors that might show up while reading a database.

In the following example, locate uses a different database to perform the search. The command first reports that the database doesn’t exist.

However, specifying the -q option suppresses the error:

Limit the Number of Search Results

Limit the number of search results with the -n option to avoid redundant results. For example, limit the search to only ten results by entering:

The output shows only the first ten files matching the search pattern.

Ignore Case Sensitive Files

By default, locate performs a case-sensitive search when processing the input query. Instruct locate to ignore case sensitivity using the -i option.

In the following example, we first searched for example_file in lowercase, and locate showed no output because the filename contains uppercase letters.

Searching for the file in uppercase shows the file’s location:

Performing the same search in lowercase and specifying the -i option ignores case-sensitivity and shows the file in the output:

Search for a File with an Exact Name

By default, locate parses the input pattern as a string and shows all files containing the input pattern within the filename. For example, searching for mysql shows all files containing the mysql string as part of the filename, instead of files whose entire filename is mysql.

Search for a file with an exact name using the -r (regular expression) option.

The output shows only the files whose filename completely matches the input pattern.

Note: The dollar sign ( $ ) at the end of a regular expression marks the end of a line. The forward slash character ( / ) denotes regular expression boundaries.

Separate Output Entries with ASCII NUL

The output entries that locate produces are separated by a newline ( \n ) character. Use the -0 option to separate entries with ASCII NUL instead of the newline character.

The default separator is no longer the newline character, and the entries are separated with ASCII NUL .

View Database Statistics

The locate command allows you to see various database statistics, including the number of directories and files stored in the database. To display database statistics, specify the -S option:

The output states which database locate is currently using, the number of directories and files, and the database size in bytes.

Note: Learn everything about databases in our comprehensive article on databases and database systems.

Update locate Database

The database that locate uses automatically updates daily at the same time. To update the database manually and make sure the file index is correct, run the following command:

The update process takes a few seconds to complete, depending on the number of files on the system.

Choose a Different mlocate Database

Instruct locate to use a database other than the default one by specifying the -d option. The feature is helpful when looking for results not present in the default mlocate database.

To specify a different database, use the following syntax:

Ignore Diacritics and Accent Differences

The locate command uses ordinary letters for result matching, which means that filenames containing letters with diacritics do not appear in the search results. Use the -t option to instruct locate to ignore such differences between letters and include diacritics in the results.

Searching for the nice-cafe pattern shows no results in the example above because the filename contains a diacritical mark. Searching for the same pattern again and specifying the -t option shows the nice-café file path as a result, ignoring the diacritic in the filename.

This guide showed how to use the locate command to quickly search for files in a filesystem. While the utility has its drawbacks, the utility is an excellent solution for finding files when speed is a priority.

For other useful Linux commands, check out our comprehensive Linux commands cheat sheet with a downloadable PDF document.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector