Question: I'm trying to get a list of packages installed which come from my company's private apt repository.

This works:

```
#!/bin/bash
fqdn=$1

for pkg in $(dpkg-query --show | awk '{print $1;}'); do
  if apt-cache showpkg $pkg | grep -q $fqdn; then
    echo $pkg
  fi
done

```

But running it on a system with ~3466 (`dpkg -l | wc -l`) packages installed takes 1m45.812s. That's an awful long time to display a "Scanning locally for installed packages" to my users.

Is there a better way to do this?

---

I tried replacing `apt-cache showpkg` with `apt show` to read the `APT-Sources:` line. This warns about apt's unstable CLI interface and takes 15m35.913s.

Answer: 
Don’t loop over the packages:

```
dpkg -l | awk '/^ii/ { print $2 }' | xargs apt-cache showpkg |
awk "/^Package:/ { package = \$2 } /$1/ { print package }" | uniq

```

This takes a couple of seconds on my system, with over 6,000 installed packages, and doesn’t involve using `/var/lib/apt` directly.

There are a few limitations, notably that it doesn’t check which *version* is currently installed v. which one are available from the repositories, and also that Debian doesn’t provide any way to determine which repository a package was actually installed from.
This one only takes `0m3.654s` but uses `/var/lib/apt`.

```
#!/bin/bash
fqdn=$1
for pkg in $(dpkg-query --show | awk -F "[ \t:]" '{print $1;}'); do
  if grep -q "Package: $pkg" /var/lib/apt/lists/${fqdn}_*_Packages; then
    echo $pkg
  fi
done

```

I understand that `/var/lib/apt` is internal to `apt` and so `apt` could choose to change the implementation and break the script. It's probably unlikely, but could happen. Instead it's normally better to use `apt` tools to access this data.