14

I need to, from a bash script, check to see if certain Ruby gems are installed .

I thought I could do something like

if ! gem list <name>; then do_stuff; fi

but testing on the command line using echo $? shows that gem list <name> returns 0 regardless of if name is actually found.

Does this mean I have to use grep to filter the output of gem list, or is there a better way I can check to see if a gem is installed?

Lee Lowder
  • 440
  • 1
  • 5
  • 17

3 Answers3

27

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).

Sven
  • 97,248
  • 13
  • 177
  • 225
  • 1
    To check if a specific version is installed, just add `--version`, e.g.: `gem list -i compass --version 0.12.4`. – moeffju Mar 27 '14 at 16:45
6

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!"
fi

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

larsks
  • 41,276
  • 13
  • 117
  • 170
4

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

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

  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 1.6.2.1
false
slm
  • 7,355
  • 16
  • 54
  • 72
  • 1
    Apologies for the downvote, but as stated in the man page for `gem query`: "The query command is the basis for the list and search commands. You should really use the list and search commands instead. This command is too hard to use." ... don't want to create bad habits in the SO community! :-) – pvandenberk Dec 29 '16 at 08:27