On a server running Ubuntu 20.04 LTS I am trying to list installed kernels with the command:
dpkg-query -W -f '${Package}\n' 'linux-image-[0-9]*'
which according to the manpage should list installed packages matching the pattern. However the output of the command includes kernel versions which have already been removed. How can I limit the output to kernels which are still installed?
The manpage on 20.04 says "all packages matching the pattern" which includes uninstalled packages. It does not claim to limit output to installed packages.
Add the Package state to your output
dpkg-query -W -f '${db:Status-Status} ${Package}\n' 'linux-image-[0-9]*'
Filter the output using the package state field. All values except "not-installed" mean the package is at least partly installed.
dpkg-query -W -f '${db:Status-Status} ${Package}\n' 'linux-image-[0-9]*' | awk '$1 != "not-installed" {print}'
Limit the output to the package name
dpkg-query -W -f '${db:Status-Status} ${Package}\n' 'linux-image-[0-9]*' | awk '$1 != "not-installed" {print $2}'