How to uninstall all ruby gems in one line

Update: whilst this post is still useful, I now recommend that people use rvm to manage their gems, which makes the following post redundant as rvm allows you to quickly and easily delete gemsets at will. If you haven’t started using it yet, why not?

Today I found myself needing to uninstall all the gems installed on my system. As I didn’t want to uninstall each gem by hand (there was quite a long list) I started poking about for options in the gem command. Unfortunately the ruby gems tool does not have an option to uninstall all gems at once, so something else was required. Enter a bit of command line magic!To uninstall all ruby gems in one line you can use the following:

gem list --no-version | xargs gem uninstall -aIx

For command line gurus (that’s not me btw), this one liner should be straight forward enough. For those who don’t eat and breath unix shell, I’ll break down what the command does so it is easier to understand.

Break it down!<MC Hammer/>

The first part of this command is:

gem list --no-version

This lists all the currently installed gems. The –no-version flag tells the gem command to list the gems without the installed versions. We do this because we just want the bare names to use in the next part.

The next part of the command is:

gem uninstall -aIx <Gem Name>

Which you may have guess uninstalls the gem that is named <Gem Name>, The -aIx options do the following:

-a  Uninstall all matching versions.

So if we have multiple versions of the Gem installed, remove them all.

-I  Ignore dependency requirements while uninstalling.

We want to ignore dependencies, otherwise the removal of a gem might be interrupted because other gems depend on it.

-x  Uninstall applicable executables without confirmation.

Gems (like rake) install executable scripts along with the gem on installation. We want these files removed as well.

Tying it all together

Now, here is the tricky bit where we tie the two commands together using xargs. From the manpage: “xargs reads items from the standard input, delimited by blanks… or newlines, and executes the command“.

So we pipe (‘|’) the output of the gem list command to xargs, and tell xargs to execute the gem uninstall command for each one of the gems listed by gem list. The result is that each and every gem is uninstalled.

The result is the elegant one liner we saw above:

gem list --no-version | xargs gem uninstall -aIx

Note: if you are not using rvm gemsets, and your gems are installed to the system, you may need to execute the gem uninstall command as sudo. If this is the case the entire command will look like:

gem list --no-version | xargs sudo gem uninstall -aIx

Happy hacking!

-James