Finding packages to install with fzf

fzf is a general-purpose command-line fuzzy finder that takes any list of strings as input, performs incremental fuzzy search based on the user's input and returns the selected item(s).

One of the ways in which I employ this program is to look for a package to install on my machine when I don't know its name. This happens a lot when trying to install a program and an error occurs, saying a core library is missing. I don't seem to be able to ever remember what package these libraries correspond to (is it libev-dev or libx-dev, libev-xcb-dev..., ugh!) what versions I can install, or even if there are any available.

On distributions shipping apt as default package manager, the apt-cache dump command will output all the available packages. The problem is that this command would actually print a lot more than just a simple list; it shows, for each package, the description, version, dependencies, ... and, even if using a pager like less, it becomes impossible to find something.
To only output the actual names of the packages:

apt-cache dump | grep "Package:" | awk '{print $2}'

Here, with grep I am only selecting the lines containing the packages' names and, by piping these into awk, I can decide to only print the second item of each line, thus discarding the "Package:" part.
This list of names can now be fed to fzf so that I can fuzzy find what I am looking for:

packages=`apt-cache dump | grep "Package:" | awk '{print $2}' | \
            fzf -m --prompt="Select packages: "`

Notice the -m flag, it allows for multiple selection. What this means is that, before pressing Return to select the item under the cursor, I can press Tab or Shift+Tab to "save for selection" the current item and fzf won't return the output just yet, so that I can keep searching and selecting other items.

At the end of the selection process the packages variable will either be empty (in which case nothing more has to be done), or it will contain the list of selected packages, ready to be installed with the most famous apt command:

sudo apt install $packages

The code for the entire script is the following:

#!/bin/bash
packages=`apt-cache dump | grep Package: | awk '{print $2}' | \
          fzf -m --prompt="Select packages: "`

if [[ -z $packages ]]; then
    echo "No packages selected." ; exit
fi
sudo apt install $packages