Rebuilding a corrupt RPM database

The RPM database is held in /var/lib/rpm . If it gets damaged it can be rebuilt using the following procedure (first posted to the linux.redhat.rpm newsgroup by Brian Ollenberger)

  1. mv /var/lib/rpm /var/lib/OLDrpm

  2. Load and mount the Red Hat install CD

  3. rpm --nodeps --force --justdb -i /mnt/cdrom/RedHat/RPMS/* - to create a new database containing everything on the Red Hat install CD (you may need to sepcify --ignoresize and/or --noscripts if you get any complaints)

  4. Next run the following script to work out what is actually installed and remove bogus entries from the database. (Note: If you get any messages stating "Package XYZ is missing some files" you will need to determine manually if these packages are installed or not and take the appropriate action)

    #!/bin/bash
    #rpmdel:  (C)2001 Brian Ollenberger
    
    rm -f rpmdel.log
    echo "Listing packages..."
    for i in `rpm -qa --queryformat %{NAME}'\n'`
    do
     FILEMISSING=`rpm -V $i | sed s/"missing    "//g | grep "^/" -c`
     if [ $FILEMISSING -gt 0 ]
     then
      TOTALFILES=`rpm -q --filesbypkg $i | grep "" -c`
      if [ $FILEMISSING -eq $TOTALFILES ] #no files - delete package from db
      then
       rpm --justdb --nodeps -e $i
       if [ $? -eq 0 ]
       then
        echo "$i" >> rpmdel.log
       else
        echo "An error occured deleting package $i."
       fi
      elif [ $FILEMISSING -lt $TOTALFILES ] #partially missing
      then
       echo "Package $i is missing some of its files."
      else #THIS SHOULD NOT RUN
       echo "*Package $i is missing more files than it should have."
       echo "* This should NOT happen. Check this package carefully."
      fi
     fi
    done
    
    
  5. As my corruption occurred during the upgrade of rpm I needed to run rpm --rebuilddb I would suggest only doing this if your still getting some errors. (Note: the rpm-build package is required for this)