简体   繁体   English

如何在 bash 脚本中检查机器上是否安装了 gem?

[英]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.但前提是bundlerubocop gem 安装并存在于机器上。 If the checks for the existence of these gems fail, ignore the command and exit.如果检查这些 gem 的存在失败,忽略该命令并退出。

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?也许我应该使用bundle --version看看命令是否崩溃? Thank you in advance.先感谢您。

You can grep your installed gems like this您可以像这样 grep 已安装的 gem

#!/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):之前建议的替代方法:不是测试是否安装了 gem,而是测试是否有适当的命令可用(不一定相同):

#!/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) (这个脚本可能会更好,例如,报告所有丢失的命令,而不是只遇到第一个,但这只是一个简单的草图来说明这个想法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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