Sunday, 2010-04-11 15:02 MDT

pre, a package scanning script

#! /bin/sh

# pre, a script to scan the rpm or deb database for package names.

# Time-stamp: <2009-11-06 09:11:03 ccurley pre>

# Copyright 2000 through the last date of modification Charles
# Curley. Released under the GPL.

# I keep my copy in /usr/local/bin, where both root and non-root users
# can use it.

# Typical usage: pre libpng zlib | sort

# You can also use the output field delimiters to select the field you
# want. For example, virulent vociferous vi villeins can get rid of
# emacs with the following:

# for i in $( pre emacs | cut -f1 ) ; do aptitude purge $i ; done

# Nattering nabobs of nano can use a regex similarly:

# for i in $( pre emacs ^vim | cut -f1 ) ; do aptitude purge $i ; done

GREPCMD=egrep

argc="${#@}";
# echo there are ${argc} arguments.

if [ $argc -gt 1 ] ; then
  # build multiple alternatives argument to egrep, e.g. (foo|bar|baz).
  args="(";
  for arg in "$@"; do
    # echo $arg
    args="${args}${arg}|";
  done
  args=$(echo $args | sed s/"|$"/")"/)
else
  args=$@;
fi

# Why tab as the delimiter? That's cut's default delimiter. OK, it's
# ugly. If you don't like it, change it:

# pre emacs | sed 's/\t/|/g'

# echo "${args}";
if [ -e /bin/rpm ] ; then
  rpm -qa  --queryformat "%{NAME}\t%{VERSION}\t%{RELEASE}\t%{ARCH}\n" | ${GREPCMD} -i "${args}"
else
  dpkg-query --showformat='${Package}\t${Version}\t${Revision}\t${Architecture}\n' --show  | ${GREPCMD} "$args"
fi

"pre" is short for "present", i.e. which packages are present?

Another use is finding out exactly which kernels you have installed. On Ubuntu:

root@dragon:~# pre ux-im | sort ; uname -r
linux-image-2.6.31-17-generic   2.6.31-17.54            i386
linux-image-2.6.31-19-generic   2.6.31-19.56            i386
linux-image-2.6.31-20-generic   2.6.31-20.58            i386
linux-image-generic     2.6.31.20.33            i386
2.6.31-20-generic
root@dragon:~#

Addendum, 2010-10-27: You can also pipe the output to other tools. Here's how I use it to clean out multiple kernels after an upgrade:

for i in $( pre linux-image-2.6.31 | cut -f1 ) ; do echo $i ; done | xargs aptitude -y purge

Posted by Charles Curley | Permanent link | File under: scripts, linux