Search code examples
rubysshrbenv

Respect rbenv when running commands over ssh


I have a headless Ubuntu 18.04 VM where I'm installing a Rails application on top of rbenv.

I want to be able to automate some administrative operations so I can run them locally and have my script execute the commands over ssh. However when I do this, I get the system ruby instead of the rbenv ruby. If I ssh directly to the box, then I get the correct rbenv ruby.

Example:

ubuntu:~$ cat show-ruby.sh
which ruby
ruby --version
ubuntu:~$ bash show-ruby.sh
/home/ubuntu/.rbenv/shims/ruby
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
laptop:~$ ssh ubuntu 'bash show-ruby.sh'
/usr/bin/ruby
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]

rbenv is initialized in my .bashrc file:

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

So I tried adding source ~/.bashrc to the top of my show-ruby.sh test script but it doesn't make a difference. Any ideas how I can force my remotely executed scripts to respect my rbenv-installed ruby?


Solution

  • rbenv triggers from an initialization installed in .bashrc. However, that initialization only occurs for an interactive shell. You can force a bash shell to be interactive with the -i flag:

    laptop:~$ ssh ubuntu 'bash -i show-ruby.sh'
    /home/ubuntu/.rbenv/shims/ruby
    ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]