Checking if a ruby gem is installed from bash script

Solution 1:

gem list <name> -i will return the string true if the gem is installed and false otherwise. Also, the return codes are what you would expect.

For more informations, see gem help list.

Edit: @Riateche correctly observed that this might give false positives if you search for a gem name that is a substring of an otherwise installed gem. To avoid this, use a regex syntax:

gem list '^<name>$' -i

(Example: gem list '^mini$' -i).

Solution 2:

It looks as if the gem spec command will fail with an error if the named gem is not installed. So:

if ! gem spec <name> > /dev/null 2>&1; then
  echo "Gem <name> is not installed!"

I don't know if this is the canonical way of solving this, but it works.

Solution 3:

You can also use the query sub-command to the gem command.

$ gem query -i -n bundler 
usage excerpt
$ gem help query
Usage: gem query [options]

    -i, --[no-]installed             Check for installed gem
    -I                               Equivalent to --no-installed
    -v, --version VERSION            Specify version of gem to query
                                     for use with --installed
    -n, --name-matches REGEXP        Name of gem(s) to query on matches the
                                     provided REGEXP

Will also look for specific versions as well, using the -v switch.

$ gem query -i -n bundler -v