Linux apt get reinstall

Как пользоваться 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 — переустановить пакет если он уже установлен;

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

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

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

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

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

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

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

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

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

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

sudo apt list —all-versions

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

Источник

How to reinstall a package using ‘apt-get’?

These are great two separate questions. One is how to reinstall a package, which is in the title and which is answered. The other one is, how to deal with aptitude crash on a too wide terminal.

5 Answers 5

$ man apt-get | grep reinsta -A2 --reinstall Re-Install packages that are already installed and at the newest version. Configuration Item: APT::Get::ReInstall. 

So, to use it to reinstall aptitude use:

sudo apt-get install --reinstall aptitude 

-A5 shows the matched line plus the following 5 lines. — stops parsing of options, thus interpreting anything that comes after as positional arguments, avoiding having to escape the dash in the expression -A which would otherwise be interpreted as an option to grep itself.

You can reinstall a package with sudo apt-get install —reinstall packagename . This completely removes the package (but not the packages that depend on it), then reinstalls the package.

This can be convenient when the package has many reverse dependencies.

@Cerin: I wouldn’t call the other answers overly snarky: even the «read the man page» one actually gave the answer as well as how to find it.

Читайте также:  Линукс на внешний диск

@DavidSpillett, I strongly disagree. The man pages are usually very poorly written and are very unfriendly to newbies. For example, the paragraph on the «—reinstall» option doesn’t mention that you have to use it with the «install» argument. A newbie might rightfully ask «why do I have to tell it to install AND reinstall?» An answer telling someone to RTFM is the worst kind of answer and it pains me to see it with the most votes, especially when a complete and actually helpful answer is near the bottom.

Sometimes you need to restore config files too! not just reinstall.

sudo apt-get install —reinstall xxxx

Reinstall the application, keeps the config files.

This could be helpful, but sometimes you need to start fresh, so what I use is this:

sudo dpkg -r xxxx //to remove that xxxx package sudo dpkg -P xxxx //to purge all related files 

And if you need to restore config files only, in some cases (if they are managed by ucf) you should use UCF_FORCE_CONFFMISS=1 apt-get —reinstall install [pkgname] .

This answer deserves a BIG upvote.This is what you need when you want to «fully reinstall» a package. E.g. a simple —reinstall of vsftpd doesn’t re-create the config file, even if the file doesn’t exist anymore. A «Remove+Purge+(Re)install» does the job instead.

You should be safe to remove aptitude and reinstall, as that won’t affect the other apt utilities. So: apt-get remove aptitude followed by apt-get install aptitude , or if that still fails try apt-get purge aptitude followed by apt-get install aptitude .

Before doing either of the above, I recommend a full file-system and bad-block check in case there is a problem there that caused the problem (depending on the problem, if there is one, further activity could make things worse). Also, make sure you review what will be removed in the remove/purge step before letting it proceed (it should pause to ask for permission if anything extra is changed as a result of removing that one package), to double check my thought that this is safe.

It’s a long time ago that I did things like a full filesystem check or similar. Could you please give me a short hint howto do that?

fsck -f such as fsck /dev/sda1 . The filesystem will need to be unmounted or mounted read-only at the time so as this is likely to be your root filesystem you should reboot into single-user-mode or boot from something else like a live cd.

You can use tune2fs to mark the filesystem as having been mounted more times than its set limit, that should force a check next boot. Assuming the filesystem is ext2/3/4: tune2fs -C 99 , or in case you have mount count based checking turned off, turn it on at the same time with something like tune2fs -c 17 -C 99 .

Читайте также:  Jetbrains toolbox remove linux

Источник

How to Use apt-get reinstall on Debian and Ubuntu

When files in a package are modified or accidentally removed, it can damage the system. Installing the package again resolves the problem in most cases. However, using the apt-get install command will return an error, given that the package is already present.

The —reinstall flag is a shortcut for an apt-get command used to reinstall packages, using the most up-to-date versions. This is useful for packages with many reverse dependencies.

In this tutorial you will learn how to use apt-get reinstall to reinstall packages on Debian and Ubuntu.

How to use apt-get reinstall on Debian and Ubuntu

Note: Using the —purge remove option to remove packages and installing them again achieves similar results. However, it also erases configuration files.

Reinstall Packages Using apt-get

Using the —reinstall command is a simple process. The syntax is as follows:

sudo apt-get --reinstall install PackageName

If you wish to reinstall more than one package, you can list them all in one line:

sudo apt-get --reinstall install PackageName1 PackageName2

Reinstall htop Using apt-get

This is how to reinstall htop, an interactive process viewer on Ubuntu, using the —reinstall flag.

sudo apt-get --reinstall install htop

The output should look like this:

Reinstall htop using apt-get

Reinstall Packages Using aptitude Command

Aptitude is a graphical user interface for the apt package manager. However, it can be used with the command line too.

If you wish to reinstall a package with aptitude, use the following syntax:

sudo aptitude reinstall PackageName

Reinstall a package using the aptitude command

Note: Use sudo aptitude reinstall ‘~i’ command if you wish to reinstall ALL packages.

Reinstall apt After You Accidentally Removed It

If you accidentally remove apt, for example by purging it using —force-* option, install it again in three simple steps:

1. Go to https://packages.debian.org/apt to search for the release of your choice. Avoid testing or unstable releases.

2. Choose the version number and download the package for your architecture.

Download the apt package for your architecture

sudo dpkg -i apt_0.5.4_i386.deb

Replace the version and architecture in the example as necessary.

Install the apt package

After reading this article, you should be able to reinstall packages using both apt-get and aptitude commands, as well as to restore apt itself if it is removed accidentally.

For more details on the apt package manager, read our article on how to manage packages on Ubuntu.

Источник

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