简体   繁体   中英

How to check if a gem installed on a machine in bash script?

I want to be able to run a system command from script

bundle exec rubocop

but only if bundle and rubocop gems installed and exist on a machine. If the checks for the existence of these gems fail, ignore the command and exit.

How is it possible to setup these checks before running the command? Maybe I should use bundle --version and see if the command crashes or not? Thank you in advance.

You can grep your installed gems like this

#!/bin/bash

if ! gem list --local | grep -q 'bundler'; then
  echo 'Please install bundler first'
  exit 1
fi

if ! gem list --local | grep -q 'rubocop'; then
  echo 'Please install rubocop first'
  exit 1
fi

bundle exec rubocop

An alternative approach to the one(s) suggested before: testing not if the gems are installed, but if the appropriate commands are available (which is not necessarily the same):

#!/bin/bash

if type bundle >/dev/null 2>&1; then
  if type rubocop >/dev/null 2>&1; then
    bundle exec rubocop
  else
    echo "Rubocop seems to be not available"
    exit 1
  fi
else
  echo "Bundler seems to be not available"
  exit 1
fi

(this script could be better, for example, to report all the missing commands instead of just the 1st encountered, but it's just a quick sketch to illustrate the idea)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM