Debian как найти программу


Where »is» it? (in Debian)

  • What package is it in?
  • Where is it?

Answers to these questions and more, for your Debian system…


One of the most common questions in Debian is «Where is it?»

Fortunately, this is the sort of question that there are well-established methods of finding answers for.

Contents

  1. Where »is» it? (in Debian)

    1. A word about the tools:
  2. «When I type ‘foo’, which file gets executed?»
  3. «Where is file ‘bar.baz’ on my system?»
  4. «I have a file ‘quux’ on my system, which package does it belong to?»
  5. «I don’t have file ‘quux’ on my system, but I need it. Which package do I install?»
  6. «I installed the ‘zort’ package, now how do I know what files it gave me?»
  7. What files are used for the configuration of the ‘troz’ package?
  8. «Which package has the ‘noot’ stuff?»
  9. «What program or function do I have that does ‘snork’?»

A word about the tools:

The tools I mention here (apropos, /msg apt on ?FreeNode, dlocate, dpkg, find, grep, grep-available, locate, http://packages.debian.org/, whatis, whereis) all have many more options and much more power than that tiny bit I’ve shown here. For maximum enjoyment from these tools and others, please see their man pages.

«When I type ‘foo’, which file gets executed?»

Tools:

  • which foo

  • whereis foo

  • type foo (at least for bash users)

When you enter a program name at the command-line, the shell looks for an executable file of that name in a list of directories named by the environment variable PATH, and it runs the first matching executable it finds. You can view the current path by typing ‘echo $PATH’, and change it like any other environment variable (see your favourite shell documentation for details).

The which command will show you the full path of the executable that would be run. There is also a whereis command that will tell you the location of both the program and its man page, but whereis searches only a fixed path and will not find things in local additions to your PATH.

The type command will also show you information about commands that are not really executable files. It is itself not an executable file but a shell builtin in bash, the usual shell in debian. For help try help type.

«Where is file ‘bar.baz’ on my system?»

Tools:

  • locate bar.baz

  • find / -name bar.baz

The GNU find command is the swiss-army knife of filesystem searching tools, and it has great powers that we won’t even begin to touch upon here. We can use it in its most basic capacity to find the location of a file, like so: ‘find / -name bar.baz’. The ‘/’ here is actually the starting directory so, if you have an idea of where to start looking, you can specify it here and find won’t waste its time searching the rest of the disk. For example, if you are only looking for a bar.baz in your home directory, you would use: ‘find $HOME -name bar.baz’.

The locate command is also useful for this basic file finding task, and it will often give you results much faster than find will. It makes use of a database of most filenames on the system (this is configurable), and since this information is already all in the database, locate doesn’t have to go out and search the whole disk like find does. The usage of locate is simply ‘locate bar.baz’.

The downside of locate is that building this database of filenames has its price, so it’s usually done only once a day (by a cron job). This means that if you’re looking for a file that is less than one day old, you’ll have to force the database to update by running the updatedb (or /etc/cron.daily/find) command, or go back to using find.

Note that if the file you’re looking for has been installed by the Debian packaging system, the tools used to answer the next question will often answer this one too, so you could use those instead.

«I have a file ‘quux’ on my system, which package does it belong to?»

Tools:

  • dpkg -S quux

  • dlocate quux

  • apt-file search quux

If you would like to find out what Debian package a particular installed file is associated with, you may use either of these commands. The relationship between dlocate and dpkg -S is very much like the one between locate and find, above. dlocate is much faster, but is not always up-to-the-minute accurate with regards to newly installed files.

Note that dlocate does not come on all systems by default, so you may have to install it.

apt-file, although not the best way, can be used to find files on the system but it uses a database that may or may not be up-to-date. See the next section for more details.

«I don’t have file ‘quux’ on my system, but I need it. Which package do I install?»

Tools:

  • packages.debian.org

  • zgrep Contents-<ARCH>.gz

  • On wiki:Self:OPN IRC: /msg apt find quux

  • apt-file search quux

Finding out about files you don’t have tends to require going off-site. One source of information is the handy-dandy webform at packages.debian.org. If you’re signed on to Open Projects Network, you can also ask apt-the-IRC-bot with ‘/msg apt find quux’.

If you would like to be able to make queries on this information locally, you can get a Contents file which lists all the files in all the packages of a particular distribution. All Debian mirrors carry this file in the appropriate subdirectory under debian/dists/, and it’s named «Contents-ARCH.gz», where ARCH is the name of your machine’s architecture (e.g. i386 or powerpc). So to get the list of all files in every package of the testing distribution for the i386 architecture, you would get debian/dists/testing/Contents-i386.gz from your favourite Debian mirror.

Once you have the Contents file, you can look for a particular file by typing ‘zgrep quux Contents-<ARCH>.gz’. zgrep is just grep that lets you look through compressed files without gunzipping them first.

There is also a tool that does something similar to the method described above: apt-file. You can apt-get install apt-file then apt-file update to update its database (needed only once in a while). Then you can do apt-file search quux to find a list of all packages that contain a file with the regular expression ‘quux’ in it. The advantage of this method is it’s a debian tool, it’s easier to maintain, it’s easier to use and it works off-line. (ie. no network is needed as when using packages.debian.org).

«I installed the ‘zort’ package, now how do I know what files it gave me?»

Tools:

  • dpkg -L zort

  • dlocate -L zort

  • cat /var/lib/dpkg/info/zort.list

If you’ve just installed a package but aren’t quite sure where to start with it, you can ask for a listing of all the files it just installed. This way, you can find out the names of the documentation and executable files.

Note that dlocate does not come on all systems by default, so you may have to install it.

What files are used for the configuration of the ‘troz’ package?

Tools:

  • dlocate -conf troz

  • cat /var/lib/dpkg/info/troz.conffiles

If you want to know which files a package gets its configuration settings from, this will tell you. These files will be the ones to fiddle with to get the package tuned to your liking, although most packages do not require you to edit them.

Configuration files are also special because, unlike the other files associated with a package, they are not deleted when the package is removed. This lets you install, remove, upgrade, switch between packages, then switch back when you change your mind, without ever losing your configuration.

If you decide you’re really done with a package, purging it (instead of removing) will clean out the configuration files too.

«Which package has the ‘noot’ stuff?»

Tools:

  • packages.debian.org/

  • apt-cache search noot

  • grep-available noot

Perhaps you’re looking for a package with, say, freecell but you don’t want to search by filename because you don’t know the exact name of any file in the package. What you do want to do is to search the descriptions of available packages. Any of these methods will work. grep-available is actually just a different interface to apt-cache, but I find it to be a little more comfortably grep-like. grep-available doesn’t come by default on all systems though, so you may have to install it.

«What program or function do I have that does ‘snork’?»

Tools:

  • apropos snork

Actually, this question can often be answered by using the tools mentioned for the previous one. It’s really just an excuse for me to plug apropos. apropos searches through the one-line description of files or functions provided by that program’s man page, and returns a list of things that look relevant. For example, if I wanted to see a list of all the utilities I have on my system for working with HTML files, I’d type ‘apropos html’. For further details on any particular program, you can follow up by viewing its man page.


This page was originally written by KevinTurner on 2/25/2001. There are now other tools which either didn’t exist at the time or he just didn’t use (e.g. dpkg-iasearch and apt-file) which this document should be updated to reflect.


2002/12/08 18:51 UTC (via web): You should mention dpkg-www, it is great for newbie.


New to the wiki, I thought I’d do something useful so I completely reformatted this page so that the original HTML gobbleygook pasted by the creator was translated into wiki format that displays the page properly.

2005-03-11: AndyMorris


CategoryCommandLineInterface CategorySystemAdministration

Как найти установленное приложение ?

Автор Сергей Григорьевич, 08 февраля 2014, 09:53:54

« назад — далее »

0 Пользователи и 1 гость просматривают эту тему.

Доброе утро, коллеги.
Новичок. Дебиан 7, среда Gnome.
Понадобился пакет GPSBabel. Установил его — «Установка и удаление программ».
Попал он в группу «Стандартные», как показывает установщик. И на этом всё. Больше я его найти нигде не могу.
На рабочем столе в меню «ПриложенияСтандартные» — нет.
В Наутилусе при поиске по файловой системе тоже нет.
Чего-то недопонимаю ?
Спасибо.


Из командной строки запустите.
А вообще, посмотреть что куда кладет приложение можно командой dpkg -L имя_пакета (в данном случае gpsbabel).

Все мы где-то, когда-то и в чем-то были новичками.


Нашел. dpkg -L. Спасибо.
Лежит в /usr/bin.
Подвязал его на рабочий стол в «Стандартные». Всё красиво, но не запускается.


В консоли запустить попробуйте. Может, будет какая-то ругань, которая подскажет, куда копать.


В терминале запустил, отвечает, но, похоже не графическая программа.
Спасибо за ответы. Будем разбираться дальше.


да, оказывается запускать нужно из терминала:

$ apt-cache show gpsbabel
.....
interface::commandline,
.....



The direct answer is procps. Here is how you can find this out for yourself:

# Install apt-file, which allows you to search
# for the package containing a file
sudo apt-get install apt-file

# Update the package/file mapping database
sudo apt-file update

# Search for "top" at the end of a path
apt-file search --regexp '/top$'

The output of the final command should look something like this:

crossfire-maps: /usr/share/games/crossfire/maps/santo_dominion/magara/well/top
crossfire-maps-small: /usr/share/games/crossfire/maps/santo_dominion/magara/well/top
liece: /usr/share/emacs/site-lisp/liece/styles/top
lxpanel: /usr/share/lxpanel/profile/two_panels/panels/top
procps: /usr/bin/top
quilt: /usr/share/quilt/top

You can see that only procps provides an executable in your standard PATH, which gives a clue that it might be the right one. You can also find out more about procps to make sure like it seems like the right one:

$ apt-cache show procps
Package: procps
Version: 1:3.3.3-3

[...]

Description-en: /proc file system utilities
 This package provides command line and full screen utilities for browsing
 procfs, a "pseudo" file system dynamically generated by the kernel to
 provide information about the status of entries in its process table
 (such as whether the process is running, stopped, or a "zombie").
 .
 It contains free, kill, pkill, pgrep, pmap, ps, pwdx, skill, slabtop,
 snice, sysctl, tload, top, uptime, vmstat, w, and watch.

Время на прочтение
3 мин

Количество просмотров 286K

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

Краткая справка Debian администратора

Основное и общеизвестное

Получение информации о новых/обновлённых пакетах

sudo aptitude update

Обновление

sudo aptitude safe-upgrade

Поиск пакета по именам пакетов

aptitude search key_word

Поиск пакета по точному названию

aptitude search "^name$"

Поиск по описанию

aptitude search "?description("key_word")"

Информация о пакете

aptitude show package_name

Установка

sudo aptitude install package_name

Удаление

sudo aptitude remove package_name

Полное удаление (вместе с конфигами)

sudo aptitude purge package_name

Очистить кэш загруженных пакетов (освободить место)

aptitude autoclean # удалятся только пакеты неактуальных версий
aptitude clean # очистится весь кэш

Установка отдельно скачанного/созданного пакета (для создания пакета из сторонних исходников нужно использовать утилиту checkinstall с флагом -D)

sudo dpkg -i /path/to/package.deb

Для получения доп информации

man aptitude
sudo aptitude install aptitude-doc-en

и смотрим документацию (/usr/share/doc/aptitude/html/en/index.html), кому быструю справку по поисковым шаблонам, тому сюда — /usr/share/doc/aptitude/html/en/ch02s04.html. Если лень ставить доку, то в сети она есть.
Вводная на Debian Wiki: wiki.debian.org/Aptitude

А теперь то что не очевидно или требует полного прочтения документации

1. Как после update посмотреть какие пакеты будут обновлены?

aptitude search ?upgradable

также можно юзать (если поставить)

sudo daptup

но после его установки точно также будет себя вести и обычный update

2. Как узнать что изменилось в пакетах которые будут обновлены?
Можно пробовать

sudo aptitude changelog package_name

для каждого пакета.
Но лучше поставить apt-listchanges, тогда перед любой установкой обновлений будет показан список изменений, по умолчанию настройки не очень удобные, поэтому лучше перенастроить под себя, например, выбрать формат вывода (пока использую текст, при больших обновлениях наверно pager лучше), не слать писем, спрашивать подтверждения, выводить всю информацию. Для этого нужно запустить

sudo dpkg-reconfigure apt-listchanges

3. Что делать если обновление что-то поломало и нужно откатиться?
Отката нет, можно попробовать найти предыдущую версию пакета

sudo aptitude version package_name

и установить её

sudo aptitude install package_name=version

4. Как найти все пакеты установленные вручную?
есть вариант команды (aptitude search ‘~i!~M’), но к сожалению он не даёт желаемого результата, так что вопрос остаётся открытым, есть куча способов основанных на анализе логов

/var/log/aptitude (+ ротированные куски)
/var/log/installer/initial-status.gz
/var/log/dpkg.log (+ ротированные куски)

но простого и готового решения нет, да информация теоретически может быть потеряна при ротациях, нужно конфигурить

5. Как посмотреть список файлов в пакете?
если пакет установлен

dpkg -L package_name

для любых пакетов поставить apt-file и

apt-file list package_name

6. Как посмотреть какому пакету принадлежит файл?

dpkg -S file_name

7. Как удалить все пакеты, где есть key в названии пакета?

sudo aptitude purge ~ikey

8. Как удалить оставшиеся конфиги от удалённых пакетов?

sudo aptitude purge ~c

9. Как найти пакет пакет, в котором содержится файл lib.so:

apt-file search lib.so

10. Как сконвертировать rpm пакет в deb?

alien --to-deb /path/to/file.rpm

11. Как найти список установленных ядер?

dpkg --list linux-* | grep ii

12. Как установить пакет из testing или experimental?
На эту тему нужно писать отдельно (например так), но если кратко, то команды для этого есть

sudo aptitude -t testing package_name

или

sudo aptitude package_name/testing

13. Как удалить метапакет, но оставить одну из зависимостей?
придётся почитать документацию про ключ unmarkauto или глянуть сюда.

14. Как узнать что попало в файловую систему мимо системы управления пакетами?
Есть утилита cruft, хотя вопрос интерпретации результатов (файла report) пока открыт

sudo cruft -d / -r report --ignore /home --ignore /var --ignore /tmp

15. Какие есть дополнительные репозитории?
Debian — wiki.debian.org/UnofficialRepositories
Ubuntu — множество всяких PPA

16. Что есть ещё?
apt-cdrom
apt-spy
auto-apt. заметка на хабре
apt-key
apt-add-repository
Некоторые вещи умеет только apt-get
Есть альтернативные утилиты для управления пакетами, например wajig, который пытается вобрать в себя функционал всех остальных утилит.

17. Как найти пакеты зависящие от данного

apt-cache rdepends package_name

также может пригодится

aptitude why package_name

Благодарю всех кто помог своими советами в рассылке, жж (JackYF) и хабре ( run4way, sledopit, nazarpc, AgaFonOff, amarao, traaance, adrianopol, Karamax). Замечания и дополнения приветствуются.

Обновлено Обновлено: 01.02.2022
Опубликовано Опубликовано: 25.07.2016

Утилита find представляет универсальный и функциональный способ для поиска в Linux. Данная статья является шпаргалкой с описанием и примерами ее использования.

Синтаксис
Примеры
    Поиск по имени
    По дате
    По типу файла
    По правам
    По содержимому
    С сортировкой по дате изменения
    Лимиты
    Действия над найденными объектами
Запуск по расписанию в CRON

Общий синтаксис

find <где искать> <опции>

<где искать> — путь к корневому каталогу, откуда начинать поиск. Например, find /home/user — искать в соответствующем каталоге. Для текущего каталога нужно использовать точку «.».

<опции> — набор правил, по которым выполнять поиск.

* по умолчанию, поиск рекурсивный. Для поиска в конкретном каталоге можно использовать опцию maxdepth.

Описание опций

Опция Описание
-name Поиск по имени.
-iname Регистронезависимый поиск по имени.
-type

Тип объекта поиска. Возможные варианты:

  • f — файл;
  • d — каталог;
  • l — ссылка;
  • p — pipe;
  • s — сокет.
-size Размер объекта. Задается в блоках по 512 байт или просто в байтах (с символом «c»).
-mtime Время изменения файла. Указывается в днях.
-mmin Время изменения в минутах.
-atime Время последнего обращения к объекту в днях.
-amin Время последнего обращения в минутах.
-ctime Последнее изменение владельца или прав на объект в днях.
-cmin Последнее изменение владельца или прав в минутах.
-user Поиск по владельцу.
-group По группе.
-perm С определенными правами доступа.
-depth Поиск должен начаться не с корня, а с самого глубоко вложенного каталога.
-maxdepth Максимальная глубина поиска по каталогам. -maxdepth 0 — поиск только в текущем каталоге. По умолчанию, поиск рекурсивный.
-prune Исключение перечисленных каталогов.
-mount Не переходить в другие файловые системы.
-regex По имени с регулярным выражением.
-regextype <тип> Тип регулярного выражения.
-L или -follow Показывает содержимое символьных ссылок (симлинк).
-empty Искать пустые каталоги.
-delete Удалить найденное.
-ls Вывод как ls -dgils
-print Показать найденное.
-print0 Путь к найденным объектам.
-exec <команда> {} ; Выполнить команду над найденным.
-ok Выдать запрос перед выполнением -exec.

Также доступны логические операторы:

Оператор Описание
-a Логическое И. Объединяем несколько критериев поиска.
-o Логическое ИЛИ. Позволяем команде find выполнить поиск на основе одного из критериев поиска.
-not или ! Логическое НЕ. Инвертирует критерий поиска.

Полный набор актуальных опций можно получить командой man find.

Примеры использования find

Поиск файла по имени

1. Простой поиск по имени:

find / -name «file.txt»

* в данном примере будет выполнен поиск файла с именем file.txt по всей файловой системе, начинающейся с корня /.

2. Поиск файла по части имени:

find / -name «*.tmp»

* данной командой будет выполнен поиск всех папок или файлов в корневой директории /, заканчивающихся на .tmp

3. Несколько условий. 

а) Логическое И. Например, файлы, которые начинаются на sess_ и заканчиваются на cd:

find . -name «sess_*» -a -name «*cd»

б) Логическое ИЛИ. Например, файлы, которые начинаются на sess_ или заканчиваются на cd:

find . -name «sess_*» -o -name «*cd»

в) Более компактный вид имеют регулярные выражения, например:

find . -regex ‘.*/(sess_.*cd)’

find . -regex ‘.*/(sess_.*|.*cd)’

* где в первом поиске применяется выражение, аналогичное примеру а), а во втором — б).

4. Найти все файлы, кроме .log:

find . ! -name «*.log»

* в данном примере мы воспользовались логическим оператором !.

Поиск по дате

1. Поиск файлов, которые менялись определенное количество дней назад:

find . -type f -mtime +60

* данная команда найдет файлы, которые менялись более 60 дней назад.

Или в промужутке:

find . -mmin -20 -mmin +10 -type f

* найти все файлы, которые менялись более 10 минут, но не более 20-и.

2. Поиск файлов с помощью newer. Данная опция доступна с версии 4.3.3 (посмотреть можно командой find —version).

а) дате изменения:

find . -type f -newermt «2019-11-02 00:00»

* покажет все файлы, которые менялись, начиная с 02.11.2019 00:00.

find . -type f -newermt 2019-10-31 ! -newermt 2019-11-02

* найдет все файлы, которые менялись в промежутке между 31.10.2019 и 01.11.2019 (включительно).

б) дате обращения:

find . -type f -newerat 2019-10-08

* все файлы, к которым обращались с 08.10.2019.

find . -type f -newerat 2019-10-01 ! -newerat 2019-11-01

* все файлы, к которым обращались в октябре.

в) дате создания:

find . -type f -newerct 2019-09-07

* все файлы, созданные с 07 сентября 2019 года.

find . -type f -newerct 2019-09-07 ! -newerct «2019-09-09 07:50:00»

файлы, созданные с 07.09.2019 00:00:00 по 09.09.2019 07:50

По типу

Искать в текущей директории и всех ее подпапках только файлы:

find . -type f

* f — искать только файлы.

Поиск по правам доступа

1. Ищем все справами на чтение и запись:

find / -perm 0666

2. Находим файлы, доступ к которым имеет только владелец:

find / -perm 0600

Поиск файла по содержимому

find / -type f -exec grep -i -H «content» {} ;

* в данном примере выполнен рекурсивный поиск всех файлов в директории / и выведен список тех, в которых содержится строка content.

С сортировкой по дате модификации

find /data -type f -printf ‘%TY-%Tm-%Td %TT %pn’ | sort -r

* команда найдет все файлы в каталоге /data, добавит к имени дату модификации и отсортирует данные по имени. В итоге получаем, что файлы будут идти в порядке их изменения.

Лимит на количество выводимых результатов

Самый распространенный пример — вывести один файл, который последний раз был модифицирован. Берем пример с сортировкой и добавляем следующее:

find /data -type f -printf ‘%TY-%Tm-%Td %TT %pn’ | sort -r | head -n 1

Поиск с действием (exec)

1. Найти только файлы, которые начинаются на sess_ и удалить их:

find . -name «sess_*» -type f -print -exec rm {} ;

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

2. Переименовать найденные файлы:

find . -name «sess_*» -type f -exec mv {} new_name ;

или:

find . -name «sess_*» -type f | xargs -I ‘{}’ mv {} new_name

3. Переместить найденные файлы:

find . -name «sess_*» -type f -exec mv {} /new/path/ ;

* в данном примере мы переместим все найденные файлы в каталог /new/path/.

4. Вывести на экран количество найденных файлов и папок, которые заканчиваются на .tmp:

find . -name «*.tmp» | wc -l

5. Изменить права:

find /home/user/* -type d -exec chmod 2700 {} ;

* в данном примере мы ищем все каталоги (type d) в директории /home/user и ставим для них права 2700.

6. Передать найденные файлы конвееру (pipe):

find /etc -name ‘*.conf’ -follow -type f -exec cat {} ; | grep ‘test’

* в данном примере мы использовали find для поиска строки test в файлах, которые находятся в каталоге /etc, и название которых заканчивается на .conf. Для этого мы передали список найденных файлов команде grep, которая уже и выполнила поиск по содержимому данных файлов.

7. Произвести замену в файлах с помощью команды sed:

find /opt/project -type f -exec sed -i -e «s/test/production/g» {} ;

* находим все файлы в каталоге /opt/project и меняем их содержимое с test на production.

Чистка по расписанию

Команду find удобно использовать для автоматического удаления устаревших файлов.

Открываем на редактирование задания cron:

crontab -e

И добавляем:

0 0 * * * /bin/find /tmp -mtime +14 -exec rm {} ;

* в данном примере мы удаляем все файлы и папки из каталога /tmp, которые старше 14 дней. Задание запускается каждый день в 00:00.
* полный путь к исполняемому файлу find смотрим командой which find — в разных UNIX системах он может располагаться в разных местах.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти дежурного электрика
  • Автономная работа почты outlook как исправить
  • Как составить распоряжение для ооо
  • Как в двух массивах найти одинаковые числа
  • Уравнение касательной как найти тангенс

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии