Recursively list package dependencies

From raju

apt-rdepends can be used to recursively list all packages that are installed on a system and are dependencies of a given package. Since the output can get quite lengthy, it is prudent to redirect it to files instead of displaying it on stdout.

% apt-rdepends --state-show=Installed --state-follow=Installed PKGNAME | grep -v "^ " > deps.txt

To list both installed packages and their dependencies

% apt-rdepends --state-show=Installed --state-follow=Installed PKGNAME > details.txt

To find the number of installed packages that are needed by a given package

% apt-rdepends --state-show=Installed --state-follow=Installed PKGAME | grep -v "^ " | wc -l

As an example, the above commands for okular package would be

% apt-rdepends --state-show=Installed --state-follow=Installed okular | grep -v "^ " > deps.txt
% head deps.txt 
okular
kde-runtime
kde-runtime-data
perl
libbz2-1.0
libc6
libgcc1
...

% apt-rdepends --state-show=Installed --state-follow=Installed okular > details.txt
% head -n 50 detailed.txt
okular
  Depends: kde-runtime (>> 4:4.10)
  Depends: libc6 (>= 2.14)
  Depends: libfreetype6 (>= 2.2.1)
  Depends: libjpeg62-turbo (>= 1.3.1)
  Depends: libkactivities6 (>= 4:4.11)
...
kde-runtime
  Depends: kde-runtime-data (>= 4:4.13.3-1)
  Depends: kdelibs5-plugins (>= 4:4.13.3)
  Depends: libasound2 (>= 1.0.16)
  Depends: libattica0.4 (>= 0.4.0)
  Depends: libc6 (>= 2.15)
...
kde-runtime-data
  Depends: perl
perl
  Depends: libbz2-1.0
  Depends: libc6 (>= 2.14)
  Depends: libdb5.3
  Depends: libgdbm3 (>= 1.8.3)
  Depends: perl-base (= 5.20.2-3+deb8u1)
..
libbz2-1.0
  Depends: libc6 (>= 2.4)
  PreDepends: multiarch-support
libc6
  Depends: libgcc1
libgcc1
  Depends: gcc-4.9-base (= 4.9.2-10)
  Depends: libc6 (>= 2.14)
  PreDepends: multiarch-support
...

% apt-rdepends --state-show=Installed --state-follow=Installed okular | grep -v "^ " | wc -l        
482

Use case

When moving from Wheezy to Jessie, I wanted to upgrade the system on a package-by-package basis instead of a single apt-get upgrade/dist-upgrade.

As usual, I replaced the Wheezy entries in /etc/apt/sources.list with Jessie entries. Then I upgraded the okular package alone by doing

% sudo apt-get update
% sudo apt-get install okular

However, this does not ensure that all (recursive) dependencies of okular are actually coming from Jessie. Some of them could be coming from Wheezy. To upgrade all the recursive dependencies of okular that are currently installed, I did

% apt-rdepends --state-show=Installed --state-follow=Installed okular | grep -v "^ " | tac > deps_rev.txt
% tr '\n' ' ' < deps_rev.txt | xargs -t sudo apt-get install --download-only -y
% xargs -n1 -t -a deps_rev.txt -i sudo apt-get install {}

I used tac in the end so the most basic packages are listed at the top. All packages are downloaded first and then installed one-by-one.