rm -rf /usr/lib

So in another case of tab completion gone wrong I ended up staring at the following on my laptop.

johnf@zoot:~/dev/vquence/metrics/trunk$ sudo rm -rf /usr/lib
^C

The command only ran for a few seconds so the damage wasn’t to bad, but what did I lose?

The locate command came to my rescue. locate runs out of cron, usually once a day, and creates a database with a list of every file on your machine. You can then use it to search for files. So to work out what was missing I did the following.

# Get the list of files before we removed them
locate --regexp '.' > /tmp/before_rm

# update the locate database
sudo updatedb

# Get the list of current files on the system
locate --regexp '.' > /tmp/after_rm

# Create a list of what's missing
diff -u /tmp/before_rm /tmp/after_rm > /tmp/diff_rm
grep '^-' /tmp/diff_rm | sed -e 's/^-//' > /tmp/missing_rm

# Ask the dpkg system what packages those files belong to
for i in `cat /tmp/missing_rm`
do
    dpkg -S $i;
done | awk '{print $1}' | sed -e 's/:$//;s/,//g' > /tmp/packages

# Reinstall those packages
sudo aptitude reinstall `cat /tmp/packages`

After this process it is probably worth running the step from updatedb again to work out what is still missing.

For the record I lost 102 files and had to reinstall 97 packages.

Now back to real work!

5 thoughts on “rm -rf /usr/lib

  1. Nice trick with locate. When that happened to me I lost half of my /usr/lib/ and once I managed to reinstall dpkg and apt manually, I simply apt-get –reinstall install’ed every installed package.

    It was such a pain that I wrote safe-rm (http://www.safe-rm.org.nz), a simple rm wrapper which blacklists important directories like /usr/lib/, to make sure I never did something like that again.

    So “apt-get install safe-rm” on all your machines now 🙂

  2. A wise solution would be to ban from the shell history the rm command.

    Under bash, you can use the HISTIGNORE variable, with something like that to ignore several commands:
    HISTIGNORE=”exit:reboot:poweroff:rm”

Leave a Reply

Your email address will not be published. Required fields are marked *