Cannot change RVM gemset from shell script via `rv

2019-03-11 05:34发布

问题:

(See update at bottom)


I feel like I'm missing something terribly obvious here, but I can't change gemsets from within a shell script. This minimal script demonstrates:

#!/usr/bin/env bash

rvm gemset use "testing"

I even tried the instructions from the Scripting RVM page (although it didn't seem necessary):

#!/usr/bin/env bash

# Load RVM into a shell session *as a function*
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
  # First try to load from a user install
  source "$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"
else
  printf "ERROR: An RVM installation was not found.\n"
fi

rvm gemset use "testing"

Still no go.

Interestingly enough, if I try to run the script without first creating the "testing" gemset, I get ERROR: Gemset 'testing' does not exist, rvm gemset create 'testing' first. However, if I create the gemset and then run the script, I get no output from the script and the gemset is not changed (according to rvm info). I am able to perform other RVM gemset actions, such as creating gemsets and trusting .rvmrc files, from within the script.

[Update]

Of course, the environment is changing, as indicated by a call to rvm info from within the script. How do I get these changes to persist/affect the calling shell? Or, if that's not possible (as indicated here), is there any way to set the current RVM gemset based on input to a script?

回答1:

Had exactly the same problem, and here's the solution:

#!/bin/bash

# IMPORTANT: Source RVM as a function into local environment.
#            Otherwise switching gemsets won't work.
[ -s "$HOME/.rvm/scripts/rvm" ] && . "$HOME/.rvm/scripts/rvm"

# Enable shell debugging.
set -x

rvm 1.9.2@gemset_a
rvm gemdir
gem env gemdir

rvm 1.9.2@gemset_b
rvm gemdir
gem env gemdir

What I've found out is that your interactive shell has got rvm() and its helpers, whereas script's environment has not got them. rvm binary is executed instead, partially working and thus causing some confusion.



回答2:

I ended up implementing the functionality I wanted as a function instead of a shell script.

function rvmrc {
  rvm gemset create $1
  rvm gemset use $1
  echo "rvm gemset use $1" > .rvmrc
  rvm rvmrc trust
}


标签: bash rvm