Linux apt get find

Using apt-get Commands In Linux [Complete Beginners Guide]

Last updated October 29, 2020 By Abhishek Prakash 215 Comments

Brief: This beginner’s guide shows you what you can do with apt-get commands in Linux, how to use them to find new packages, install and upgrade new packages, and clean your system.

If you have started using Ubuntu or any Ubuntu-based Linux distribution, such as Linux Mint, elementary OS, etc., you must have come across the apt-get command by now.

In fact, first in the list of things to do after installing Ubuntu is to use apt-get update and apt-get upgrade. Now, you might be aware of a few apt-get commands and their usage, but you might not be aware of some others.

In this guide for beginners, I am going to explain various of apt-get commands with examples so that you can use them as well as an expert Linux user.

Download apt-get command cheatsheet for future reference. You can print it or save it for offline viewing.

What is apt-get?

Ubuntu is derived from Debian Linux. Debian uses the dpkg packaging system. A packaging system is a way to provide programs and applications for installation. This way, you don’t have to build a program from the source code.

APT (Advanced Package Tool) is the command line tool to interact with this packaging system. There are already dpkg commands to manage it, but apt is a more user-friendly way to handle packages. You can use it to find and install new packages, upgrade packages, clean your packages, etc.

There are two main tools around APT: apt-get and apt-cache. apt-get is for installing, upgrading, and cleaning packages, while apt-cache command is used for finding new packages. We’ll see all of these commands with examples later in this guide.

I am using Linux Mint 18 in this tutorial, but you can use any other Ubuntu-based Linux distribution, such as elementary OS, Linux Lite, etc.

Using apt-get commands

Let’s start with apt-get commands. You just cannot escape this command. It’s better to have an understanding of it, so that you can handle your Linux system in a slightly better way.

Update the package database with apt-get

apt-get basically works on a database of available packages. If you don’t update this database, the system won’t know if there are newer packages available or not. In fact, this is the first command you need to run on any Debian-based Linux system after a fresh install.

Updating the package database requires superuser privileges, so you’ll need to use sudo.

When you run this command, you’ll see the information being retrieved from various servers.

You’ll see three types of lines here: hit, get, and ign. Let me explain them to you:

  • hit: there is no change in the package version
  • ign: the package is being ignored. There could be various reasons for that. Either the package is so recent that it doesn’t even bother to check for a new version, or there was an error in retrieving the file but error was trivial and thus it is being ignored. This is not an error. There is no need to be worried.
  • get: There is a new version of the package available. apt-get will download this information (not the package itself). You can see that there is downloaded information on the ‘get’ lines in the screenshot above.

Upgrade installed packages with apt-get

Once you have updated the package database, you can upgrade the installed packages. The most convenient way is to upgrade all the packages that have updates available. You can use the command below for this purpose:

Читайте также:  Ветки реестра для автозагрузки windows

To upgrade only a specific program, use the command below:

There is another way to perform a complete upgrade, by using the command below:

But you should avoid using this command. I’ll explain why in the next section.

Difference between upgrade and dist-upgrade

The command apt-get upgrade is very obedient. It never tries to remove any packages or tries to install a new package on its own.

The command apt-get dist-upgrade, on the other hand, is proactive. It looks for dependencies with the newer version of the package being installed and it tries to install new packages or remove an existing ones on its own.

It sounds like dist-upgrade is more powerful and intelligent, doesn’t it? But there is a risk with it.

See, it has a “smart” conflict resolution system. It will attempt to upgrade the most important packages, at the expense of the less important ones. This may lead to the removal of some packages, which you might not want. This is the main reason why dist-upgrade should be avoided on production machines.

What is the difference between apt-get update and apt-get upgrade?

This is a very common confusion. You are not the only one to be confused by the terms update and upgrade.

Though it sounds like apt-get update should update the packages, that’s not true. apt-get update only updates the database of available packages. For example, if you have XYX package version 1.3 installed, after apt-get update, the database will be reflect that the newer version 1.4 is available.

When you do an apt-get upgrade after apt-get update, it upgrades the installed packages to the newer version.

This is the reason why the fastest and the most convenient way to update Ubuntu is to use this command:

Using apt-cache commands to search for packages

I’ll be honest with you, this is not my preferred way of searching for packages. But this comes in pretty handy when you are looking for some specific library.

All you need to do is to use the following command (you don’t even need sudo here):

You don’t need to know the exact name of the package. It searches in package names and their short descriptions, and shows result based on that.

If you just want to search the apt packages with specific package names, you can use the command below:

This gives you the list of all the packages starting with your search term.

Once you know the exact package name, you can get more information about it, such as version, dependencies, etc., by using the command below:

How to install new packages with apt-get

If you know the name of the package, you can easily install it using the command below:

Just replace the

with your desired package. Suppose I wanted to install Pinta image editor. All I’d need to do is use the command below:

The good thing about this command is that it has auto-completion. So if you are not sure about the exact package name, you can type a few letters and press tab, and it will suggest all the packages available with those letters. For example:

How to install multiple packages

You are not restricted to installing just one package at a time. You can install several packages at a time by providing their names:

What if you run install on an already installed package?

Suppose you already have a package installed, but you used the install command for it anyway. apt-get will actually look into the database, and if a newer version is available, it will upgrade the installed package to the newer one. So no harm is done by using this command — unless you don’t want the package to be upgraded.

How to install packages without upgrading

Suppose for some reason you want to install a package but don’t want to upgrade it if it is already installed. It sounds weird, but you may have reasons to do that.

For that case, you can use the no-upgrade flag in the following manner:

How to only upgrade a package, not install it

In case you want to upgrade a package provided it’s already installed, but don’t want to install it if it’s not, you can do that with the following command:

How to install a specific version of an application

By default, the latest version available in the repository will be installed for any application. But if, for some reason, you don’t want to install the latest version, you can specify the package version number. (You would need to know the exact version number that you wanted to install).

Читайте также:  Linux mint не запускается lightdm

All you need to do is to add the version number to the name of the package:

How to remove installed packages with apt-get

Installing packages isn’t the only thing you can do with apt-get. You can also remove packages with it. All you need to do is to use the command in this manner:

Auto-completion works here as well. So just start typing package name and press tab, and it will suggest all the installed packages starting with those letters.

Another way of uninstalling packages is to use purge. The command is used in the following manner:

What is the difference between apt-get remove and apt-get purge?

  • apt-get remove just removes the binaries of a package. It doesn’t touch the configuration files
  • apt-get purge removes everything related to a package, including the configuration files

So if you have “removed” a particular piece of software and then install it again, your system will have the same configuration files. Of course, you will be asked to override the existing configuration files when you install it again.

Purge is particularly useful when you have messed up with the configuration of a program, when you want to completely erase its traces from the system and start afresh.

Most of the time, a simple remove is more than enough for uninstalling a package.

How to clean your system with apt-get

Oh yes! You can also clean your system with apt-get and free up some disk space.

You can use the command below to clear apt cache (locally saved retrieved package files):

Another way is to use autoclean. Unlike the above clean command, autoclean only removes those retrieved package files that have a newer version now, and so won’t be used anymore.

Another way to free up disk space is to use autoremove. It removes libraries and packages that were installed automatically to satisfy the dependencies of another installed package. If that package is removed, these automatically installed packages are useless in the system. This command removes such packages.

This is a command-line way of cleaning a Linux system. If you prefer a GUI, here are some CCleaner alternatives for Linux which you can use on Ubuntu and Ubuntu-based Linux distributions.

Your input

There is more to apt-get, but this much should give you a pretty good start. You can always look up the man pages to get more information.

How do you like this guide to apt-get commands in Linux? Was it helpful to you and clear enough to understand? Your feedback will help in creating more such guides in the near future.

Like what you read? Please share it with others.

Источник

Как пользоваться apt

Пакетный менеджер Apt или Advanced Package Tool используется во множестве дистрибутивов, основанных на Debian или Ubuntu, а таких дистрибутивов сейчас очень много. Этот пакетный менеджер поддерживает все необходимые функции, вы можете устанавливать и удалять пакеты, обновлять то, что было уже установлено, искать пакеты, устанавливать их из файла или загружать без установки. При этом все зависимости будут разрешаться автоматически.

Утилита apt ничем не уступает пакетному менеджеру yum, используемому в RPM дистрибутивах, да, здесь все ещё не поддерживается частичное обновление пакетов, как в Zypper, но в целом всё выглядит очень неплохо. В этой статье мы подробно рассмотрим как пользоваться apt в Linux для решения задач работы с программами.

Синтаксис и опции apt

Синтаксис команды apt очень простой и похож на другие команды Linux:

$ apt опции команда параметры_команды

Опции указывают общее поведение утилиты, команда — действие, которое надо выполнить, а в параметрах команды обычно передается имя пакета, с которым следует работать, например, установить или удалить. Вот основные опции утилиты:

  • -v, —version — выводит версию утилиты;
  • -h, —help — выводит справку по использованию утилиты;
  • -y, —yes — автоматически отвечать «да» на все возникающие вопросы;
  • —assume-no — автоматически отвечать «нет» на все возникающие вопросы;
  • -d, —download-only — только скачать пакеты и больше ничего не делать;
  • -f, —fix-broken — исправить недостающие зависимости;
  • —no-download — ничего не загружать, использовать только пакеты из кэша;
  • -s, —simulate — режим симуляции, никакие операции не выполняются, только выводится информация на экран;
  • —allow-unauthenticated — позволяет установить пакеты, из репозиториев, для которых нет GPG подписи;
  • —no-install-recommends — не устанавливать рекомендованные пакеты, по умолчанию будут установлены;
  • -m, —ignore-missing — игнорировать пакеты, которые существует;
  • -q, —quiet — выводить минимум информации, не показывать прогресс бар;
  • -V, —verbose-versions — показывать полные версии обновленных пакетов;
  • —only-upgrade — не устанавливать новые пакеты, только обновлять;
  • —allow-downgrades — разрешить откатывать версию пакетов;
  • —reinstall — переустановить пакет если он уже установлен;
Читайте также:  Как убрать выделение значков рабочего стола windows

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

  • install — установить пакет;
  • remove — удалить пакет, конфигурационные файлы, которые были изменены в вашей системе удалены не будут;
  • purge — полностью удалить пакет, вместе со всеми его конфигурационными файлами;
  • autoremove — очистить ненужные пакеты;
  • autoclean — очистить кэш пакетов;
  • update — обновить списки пакетов из репозиториев;
  • upgrade — обновить версию пакета до последней, если пакет не указан будут обновлены все пакеты;
  • full-upgrade — полное обновление системы, включая удаление несовместимых или больше ненужных пакетов;
  • list — список установленных пакетов;
  • search — поиск пакетов;
  • show — посмотреть информацию о пакете;
  • download — скачать пакет в текущую папку;
  • edit-sources — открыть с настройками репозиториев в текстовом редакторе.
  • source — скачать исходный код пакета в текущую папку;
  • build-dep — установить зависимости необходимые для сборки выбранного пакета;

Дальше рассмотрим несколько примеров работы с apt, которые пригодятся как начинающим, так и более опытным пользователям.

Как пользоваться apt

1. Обновление пакетов

Сначала давайте обновим список пакетов apt из репозиториев. Репозитории находятся на удалённых серверах и когда утилита apt ищет пакет для установки, естественно, что она не обращается ко всем репозиториям подряд чтобы узнать где он находится. В системе уже есть сохранённых кэш информации о том, какие пакеты вообще есть и где их можно скачать. Для обновления этого кэша используйте команду update:

sudo apt update

Во время загрузки URL репозиториев обозначаются специальными префиксами, вот что они означают:

  • Hit (Сущ) — список не изменился с момента предыдущей загрузки;
  • Ign (Игн) — репозиторий игнорируется, либо он слишком новый, либо произошла незначительная ошибка во время загрузки;
  • Get(Пол) — доступна новая версия и она будет загружена.

Когда кэш обновлен вы можете посмотреть для каких пакетов доступны обновления:

sudo apt list —upgradable

Аналогично можно посмотреть установленные пакеты apt:

sudo apt list —installed

Или всех доступных:

sudo apt list —all-versions

Затем можно обновить все пакеты в системе:

sudo apt full-upgrade

2. Установка пакетов

Чтобы установить пакет apt используйте команду install, например, для установки программы Gimp используйте команду install:

sudo apt install gimp

Если пакет установился неверно и вы хотите его переустановить, можно использовать опцию —reinstall:

sudo apt install gimp —reinstall

Как видите, опции можно указывать не только перед командой, но и после неё, аналогично можно установить несколько пакетов сразу, например:

sudo apt install gimp inkskape -y

Чтобы не подтверждать установку вручную используем опцию -y. Допустим вы установили пакет с помощью dpkg и теперь хотите установить для него зависимости, запустите команду install без параметров с опцией -f или —fix-broken:

sudo apt install —fix-broken

Можно скачать deb пакет в текущую папку без установки:

apt download gimp

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

sudo apt install gimp_2.8.22-1_amd64.deb

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

sudo apt install linux-headers-generic=4.15.0.20.23

Чтобы найти доступные версии можно использовать команду policy. Она отображает информацию о том какая версия установлена, а также какие версии доступны:

sudo apt policy linux-headers-generic

Если вы не знаете как точно называется пакет, можно выполнить поиск пакетов apt с помощью команды search:

sudo apt search gimp

3. Удаление пакетов

Чтобы удалить ненужный пакет используйте команду remove:

sudo apt remove gimp

Однако если вы изменяли какие-либо конфигурационные файлы из состава пакета, то при таком способе удаления они останутся в системе, чтобы удалить всё полностью используйте команду purge:

sudo apt purge gimp

Чтобы удалить лишние пакеты, которые в системе больше не нужны выполните команду autoremove:

sudo apt autoremove

А для очистки кэша пакетов — autoclean:

sudo apt autoclean

Выводы

В этой статье мы рассмотрели примеры использования и основные команды apt Ubuntu, как видите, команд у этой утилиты хватает на все случаи жизни. Но, как видите, всё очень просто если разобраться. Я не рассказал только об одной команде, попробуйте ввести в терминале apt moo, увидите что будет. Это небольшая пасхалка от разработчиков.

Источник

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