Product SiteDocumentation Site

6.2. Los programas aptitude, apt-get y apt

APT is a vast project, whose original plans included a graphical interface. It is based on a library which contains the core application, and apt-get is the first front end — command-line based — which was developed within the project. apt is a second command-line based front end provided by APT which overcomes some design mistakes of apt-get.
Both tools are built on top of the same library and are thus very close, but the default behavior of apt has been improved for interactive use and to actually do what most users expect. The APT developers reserve the right to change the public interface of this tool to further improve it. On the opposite, the public interface of apt-get is well defined and will not change in any backwards incompatible way. It is thus the tool that you want to use when you need to script package installation requests.
Numerous other graphical interfaces then appeared as external projects: synaptic, aptitude (which includes both a text mode interface and a graphical one — even if not complete yet), wajig, etc. The most recommended interface, apt, is the one that we will use in the examples given in this section. Note, however, that apt-get and aptitude have a very similar command line syntax. When there are major differences between these three commands, these will be detailed.

6.2.1. Inicialización

For any work with APT, the list of available packages needs to be updated; this can be done simply through apt update. Depending on the speed of your connection and configuration, the operation can take a while, since it involves downloading a certain number of (usually compressed) files (Packages, Sources, Translation-language-code), which have gradually become bigger and bigger as Debian has developed (at least 10 MB of data for the main section). Of course, installing from a CD-ROM/DVD set does not require any downloading — in this case, the operation is very fast.

6.2.2. Instalación y eliminación

With APT, packages can be added or removed from the system, respectively with apt install package and apt remove package. In both cases, APT will automatically install the necessary dependencies or delete the packages which depend on the package that is being removed. The apt purge package command involves a complete uninstallation by deleting the configuration files as well.
If the file sources.list mentions several distributions, it is possible to give the version of the package to install. A specific version number can be requested with apt install package=version, but indicating its distribution of origin (Stable, Testing or Unstable) — with apt install package/distribution — is usually preferred. With this command, it is possible to go back to an older version of a package (if, for instance, you know that it works well), provided that it is still available in one of the sources referenced by the sources.list file. Otherwise the snapshot.debian.org archive can come to the rescue (see sidebar YENDO MÁS ALLÁ Versiones antiguas de paquetes: snapshot.debian.org).

Ejemplo 6.4. Installation of the Unstable version of spamassassin

# apt install spamassassin/unstable
If the package to install has been made available to you under the form of a simple .deb file without any associated package repository, it is still possible to use APT to install it together with its dependencies (provided that the dependencies are available in the configured repositories) with a simple command: apt install ./path-to-the-package.deb. The leading ./ is important to make it clear that we are referring to a filename and not to the name of a package available in one of the repositories.

6.2.3. Actualización del sistema

Se recomienda realizar actualizaciones regularmente, ya que incluyen las últimas actualizaciones de seguridad. Para actualizar, utilice apt upgrade, apt-get upgrade o aptitude safe-upgrade (por supuesto, después de apt-get update). Esta orden busca paquetes instalados que pueden ser actualizados sin eliminar ningún paquete. En otras palabras, el objetivo es asegurar la actualización menos intrusiva posible. apt-get es ligeramente más exigente que aptitude o apt ya que se negará a instalar paquetes que no estaban instalados previamente.
apt generalmente seleccionará el número de versión más reciente (excepto para paquetes en Experimental y stable-backports, que son ignorados de forma predeterminada sin importar su número de versión). Si especificó Testing o Unstable en su archivo sources.list, apt upgrade cambiará la mayor parte de su sistema en Stable a Testing o Unstable, lo que podría no ser lo deseado.
To tell apt to use a specific distribution when searching for upgraded packages, you need to use the -t or --target-release option, followed by the name of the distribution you want (for example, apt -t stable upgrade). To avoid specifying this option every time you use apt, you can add APT::Default-Release "stable"; in the file /etc/apt/apt.conf.d/local.
Para actualizaciones más importantes, tales como el cambio de una versión mayor de Debian a la siguiente, necesita utilizar apt full-upgrade. Con esta instrucción, apt completará la actualización aún si tiene que eliminar algunos paquetes obsoletos o instalar nuevas dependencias. Esta también es la orden utilizada por los usuarios que trabajan diariamente con la versión Unstable de Debian y siguen su evolución día a día. Es tan simple que casi no necesita explicación: la reputación de APT está basada en esta excelente característica.
A diferencia de apt y aptitude, apt-get no sabe cómo hacer full-upgrade command. En su lugar debería usar apt-get dist-upgrade (”distribution upgrade”), la histórica y bien conocida orden que apt y aptitude también aceptan para satisfacer a los usuarios que están acostumbrados a usarla.
The results of these operations are logged into /var/log/apt/history.log and /var/log/apt/term.log, whereas dpkg keeps its log in a file called /var/log/dpkg.log.

6.2.4. Opciones de configuración

Besides the configuration elements already mentioned, it is possible to configure certain aspects of APT by adding directives in a file of the /etc/apt/apt.conf.d/ directory or /etc/apt/apt.conf itself. Remember, for instance, that it is possible for APT to tell dpkg to ignore file conflict errors by specifying DPkg::options { "--force-overwrite"; }.
Si sólo puede acceder a la web a través de un proxy, agregue una línea como Acquire::http::proxy "http://su-proxy:3128". Para un proxy FTP, utilice Acquire::ftp::proxy "ftp://su-proxy". Para descubrir más opciones de configuración, lea la página de manual apt.conf(5) con la orden man apt.conf (para detalles sobre las páginas de manual, revise la Sección 7.1.1, “Páginas de manual”).

6.2.5. Gestión de prioridades de los paquetes

Uno de los aspectos más importantes en la configuración de APT es la gestión de las prioridades asociadas con cada origen de paquetes. Por ejemplo, podría desear extender una distribución con uno o dos paquetes más recientes de Testing, Unstable o Experimental. Es posible asignar una prioridad a cada paquete disponible (el mismo paquete puede tener varias prioridades según su versión o la distribución que lo provee). Estas prioridades influenciarán el comportamiento de APT: para cada paquete, siempre seleccionará la versión con la prioridad más alta (excepto si esta versión es anterior a la instalada y si su prioridad es menor a 1000).
APT define varias prioridades predeterminadas. Cada versión instalada de un paquete tiene una prioridad de 100. Una versión no instalada tiene una prioridad predeterminada de 500, pero puede saltar a 990 si es parte de la distribución destino (definida con la opción de línea de órdenes -t o la directiva de configuración APT::Default-Release).
You can modify the priorities by adding entries in a file in /etc/apt/preferences.d/ or the /etc/apt/preferences file with the names of the affected packages, their version, their origin and their new priority.
APT will never install an older version of a package (that is, a package whose version number is lower than the one of the currently installed package) except if its priority is higher than 1000 (or it is explicitely requested by the user, see Sección 6.2.2, “Instalación y eliminación”). APT will always install the highest priority package which follows this constraint. If two packages have the same priority, APT installs the newest one (whose version number is the highest). If two packages of same version have the same priority but differ in their content, APT installs the version that is not installed (this rule has been created to cover the case of a package update without the increment of the revision number, which is usually required).
In more concrete terms, a package whose priority is
< 0
will never be installed,
1..99
will only be installed if no other version of the package is already installed,
100..499
will only be installed if there is no other newer version installed or available in another distribution,
500....989
will only be installed if there is no newer version installed or available in the target distribution,
990..1000
will be installed except if the installed version is newer,
> 1000
will always be installed, even if it forces APT to downgrade to an older version.
When APT checks /etc/apt/preferences and /etc/apt/preferences.d/, it first takes into account the most specific entries (often those specifying the concerned package), then the more generic ones (including, for example, all the packages of a distribution). If several generic entries exist, the first match is used. The available selection criteria include the package's name and the source providing it. Every package source is identified by the information contained in a Release file that APT downloads together with the Packages files. It specifies the origin (usually “Debian” for the packages of official mirrors, but it can also be a person's or an organization's name for third-party repositories). It also gives the name of the distribution (usually Stable, Testing, Unstable or Experimental for the standard distributions provided by Debian) together with its version (for example, 10 for Debian Buster). Let's have a look at its syntax through some realistic case studies of this mechanism.
Supongamos que sólo desea utilizar paquetes de la versión estable de Debian. Aquellos provistos en otras versiones no serían instalados a menos que sean pedidos explícitamente. Puede escribir las siguientes entradas en el archivo /etc/apt/preferences:
Package: *
Pin: release a=stable
Pin-Priority: 900

Package: *
Pin: release o=Debian
Pin-Priority: -10
a=stable define el nombre de la distribución elegida. o=Debian limita el alcance a los paquetes cuyo origen es «Debian».
Let's now assume that you have a server with several local programs depending on the version 5.24 of Perl and that you want to ensure that upgrades will not install another version of it. You could use this entry:
Package: perl
Pin: version 5.24*
Pin-Priority: 1001
To gain a better understanding of the mechanisms of priority and distribution or repository properties to pin do not hesitate to execute apt-cache policy to display the default priority associated with each package source, or apt-cache policy package to display the default priority for each available version and source of a package as explained in SUGERENCIA apt-cache policy.
The reference documentation for the files /etc/apt/preferences and /etc/apt/preferences.d/ is available in the manual page apt_preferences(5), which you can display with man apt_preferences.

6.2.6. Trabajo con varias distribuciones

Siendo la herramienta maravillosa que apt es, es tentador elegir paquetes de otras distribuciones. Por ejemplo, tras instalar un sistema Stable podría desear probar paquetes de software disponibles en Testing o Unstable sin desviarse demasiado del estado inicial del sistema.
Aún cuando ocasionamente encontrará problemas al mezclar paquetes de diferentes distribuciones apt gestionará muy bien su coexistencia y limitará los riesgos de manera muy efectiva. La mejor manera de proceder es listar todas las distribuciones utilizadas en /etc/apt/sources.list (algunas personas siempre agregan las tres distribuciones, pero recuerde que Unstable está reservado para usuarios experimentados) y definir su distribución de referencia con el parámetro APT::Default-Release (revise la Sección 6.2.3, “Actualización del sistema”).
Supongamos que su distribución de referencia es Stable pero que Testing y Unstable también aparecen listados en su archivo sources.list. En este caso, puede utilizar apt install paquete/testing para instalar un paquete de Testing. Si la instalación falla debido a alguna dependencia insatisfecha, permítale resolver esas dependencias dentro de Testing agregando el parámetro -t testing. Obviamente, lo mismo aplica a Unstable.
En esta situación, las actualizaciones (upgrade y full-upgrade) se realizan dentro de Stable a excepción de los paquetes que ya fueron actualizados a otra distribución: éstos seguirán las actualizaciones disponibles en las otras distribuciones. Explicaremos este comportamiento con la ayuda de las prioridades predeterminadas de APT a continuación. No dude en utilizar apt-cache policy (revise el recuadro SUGERENCIA apt-cache policy) para verificar las prioridades otorgadas.
Todo gira alrededor del hecho de que APT considera sólo paquetes con una versión mayor o igual que la instalada (suponiendo que /etc/apt/preferences no ha sido usado para forzar prioridades superiores a 1000 para algunos paquetes).
Asumamos que instaló la versión 1 de un primer paquete de Stable y que las versiones 2 y 3 están disponibles en Testing y Unstable respectivamente. La versión instalada tiene una prioridad de 100, pero la versión disponible en Stable (la misma versión) tiene una prioridad de 990 (porque es parte de la versión de destino). Los paquetes en Testing y Unstable tienen una prioridad de 500 (la prioridad predeterminada para una versión no instalada). El ganador es, por lo tanto, la versión 1 con una prioridad de 990. El paquete «se mantiene en Stable».
Let's take the example of another package whose version 2 has been installed from Testing. Version 1 is available in Stable and version 3 in Unstable. Version 1 (of priority 990 — thus lower than 1000) is discarded because it is lower than the installed version. This only leaves version 2 and 3, both of priority 500. Faced with this alternative, APT selects the newest version, the one from Unstable. If you don't want a package installed from Testing to migrate to Unstable, you have to assign a priority lower than 500 (490 for example) to packages coming from Unstable. You can modify /etc/apt/preferences to this effect:
Package: *
Pin: release a=unstable
Pin-Priority: 490

6.2.7. Seguimiento de paquetes instalados automáticamente

One of the essential functionalities of apt is the tracking of packages installed only through dependencies. These packages are called “automatic”, and often include libraries.
With this information, when packages are removed, the package managers can compute a list of automatic packages that are no longer needed (because there is no “manually installed” packages depending on them). apt-get autoremove or apt autoremove will get rid of those packages. aptitude does not have this command because it removes them automatically as soon as they are identified. In all cases, the tools display a clear message listing the affected packages.
Es buen hábito marcar como automático cualquier paquete que no necesite directamente para que sea eliminado automáticamente cuando ya no sea necesario. apt-mark auto paquete marcará el paquete dado como automático mientras que apt-mark manual paquete realiza lo opuesto. aptitude markauto y aptitude unmarkauto funcionan de la misma forma, pero ofrecen más funcionalidad para marcar varios paquetes simultáneamente (revise la Sección 6.5.1, “aptitude). La interfaz interactiva para la consola de aptitude también facilita el revisar la «marca automática» en muchos paquetes.
Algunas personas podrían desear saber porqué un paquete instalado automáticamente está presente en el sistema. Para obtener esta información desde la línea de comandos puede utilizar aptitude why paquete (apt y apt-get no poseen una funcionalidad similar):
$ aptitude why python-debian
i   aptitude         Suggests apt-xapian-index
p   apt-xapian-index Depends  python-debian (>= 0.1.14)