如何在Shell脚本中使用RVM

18

是否可以在shell脚本中加载rvm?有人可以给出一个例子吗?当我尝试使用ubuntu系统的shell脚本时。

#!/bin/bash
rvm use 1.9.3

它给我报错了。

RVM is not a function, selecting rubies with 'rvm use ...' will not work.

You need to change your terminal emulator preferences to allow login shell.
Sometimes it is required to use `/bin/bash --login` as the command.
Please visit https://rvm.io/integration/gnome-terminal/ for a example.

可能是重复的问题:rvm安装无法工作:“RVM不是一个函数” - SirDarius
3个回答

17

您可以通过以下方式在脚本中包含rvm:

source ~/.rvm/scripts/rvm

那么rvm应该对你的脚本可用,


2
请确保使用bash来执行脚本,而不是sh。 - jbr
如何使用Bash。我创建了一个名为qst.sh的文件,并在其中编写了代码。 - user1328342
请使用"bash qst.sh"代替"sh qst.sh"。 - Aparichith
这个答案很好,也帮助了我,所以谢谢。我只想澄清一下,这行代码应该添加在你调用rvm的那一行之后。起初我以为我应该在我的命令中使用它,而不仅仅是 rvm。在我的情况下,我想要执行 rvm use system,因此我需要添加 source ~/.rvm/scripts/rvm,但仍然需要在另一行调用 rvm use system - Keith Bennett

5

如果只是想在RVM管理的Ruby(或系统Ruby)上执行命令,可以这样做:

rvm 1.9.3 exec camper_van

假设之前已经运行了rvm use 1.9.3gem install camper_van,并提供了camper_van可执行文件。

注意:RVM通常在用户启动的脚本下已经被加载 - 如果您看到RVM is not a function, selecting rubies with 'rvm use ...'这一提示,就可以确认它已经存在了。


1
# Load RVM into a shell session *as a function*
# Loading RVM *as a function* is mandatory
# so that we can use 'rvm use <specific version>'
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
  # First try to load from a user install
  source "$HOME/.rvm/scripts/rvm"
  echo "using user install $HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
  # Then try to load from a root install
  source "/usr/local/rvm/scripts/rvm"
  echo "using root install /usr/local/rvm/scripts/rvm"
else
  echo "ERROR: An RVM installation was not found.\n"
fi

命令type -fP rvm的输出是什么?给定的代码片段是shell脚本的一部分。 - Amol Pujari
1
Amol的代码需要bash,请确保您不是使用普通的sh执行脚本。 - jbr
当我在终端输入type -fp命令时,输出为/home/gaurav/.rvm/bin/rvm。实际上我是一个脚本新手。当我写下echo type -fp rvm时,相同的命令会被打印出来。 - user1328342
将以下内容添加到我的bash脚本中,这个片段会输出:“使用用户安装$HOME/.rvm/scripts/rvm”。然后,当下一行尝试“rvm use…”时,又回到了旧的“rvm不是一个函数”的错误。我们如何在Bash脚本中做些什么来“使rvm成为一个函数”,以便我们可以实际上使用它 - 比如设置ruby版本? - JosephK
非常感谢@jbr,我在bash中运行后问题得到了解决。干杯! - Ozone17

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接