DEV Community

C. Plug
C. Plug

Posted on

RVM did not work in the shell script, so I had to fix it

What happened

So I was building my portfolio site the other day and I decided to use Jekyll.

The server I'm renting can run Ruby via RVM, so with the power of symbolic links, I can pull the source on the server, build the static site there (which can be done in a breeze,) and safely serve it to the Internet.

But I ran into a problem - the script simple as this did not work:

#/usr/bin/env bash

set -eu

rvm use 2.7.2
Enter fullscreen mode Exit fullscreen mode
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 an example.
Enter fullscreen mode Exit fullscreen mode

Interesting, so RVM I use at the terminal prompt is not /usr/local/rvm/bin/rvm but a shell function that gets injected as a part of the profile.

# Run type command directly from the shell prompt
$ type rvm
rvm is a function
(function gets printed out)

# shell script that contains `type rvm`
$ ./test.sh
rvm is /usr/local/rvm/bin/rvm
Enter fullscreen mode Exit fullscreen mode

(NGL, I was fairly confused when they said "RVM is not a function..." Like, is RVM complaining that I tried to use RVM as a function when it cannot possibly be a function? Nope! What it means is that there is a shell function version of RVM and rvm must be a function to select Ruby interpreters.)

You need to source the profile yourselves

It turns out you must source the file provided by RVM. There can be two places that RVM may exist:

source "$HOME/.rvm/scripts/rvm" # $HOME installation
source "/usr/local/rvm/scripts/rvm" # System installation
Enter fullscreen mode Exit fullscreen mode

But that did not quite do the trick

Apparently, RVM relies on unbound variables, so running the script with set -eu crashes it:

#!/usr/bin/env bash

set -eu

source "/usr/local/rvm/scripts/rvm"

rvm use 2.7.2
Enter fullscreen mode Exit fullscreen mode
/usr/local/rvm/scripts/functions/support: Line 182: _system_name: Unbound variable
Enter fullscreen mode Exit fullscreen mode

So we need to temporarily allow such variables while we run all the RVM commands.

Example working script

#!/usr/bin/env bash

set +u # WTF: Avoid RVM crashing due to unbound variables

source "/usr/local/rvm/scripts/rvm"
rvm use 2.7.2

set -eu # Restore strict error checking

bundle install
JEKYLL_ENV=production bundle exec jekyll build
Enter fullscreen mode Exit fullscreen mode

Random thought

I remember having similar issue trying to use pyenv in a Jenkins-triggered shell script... It could've been an issue of the similar nature.

Oldest comments (0)