Environment Inheritance
2014-01-15
I just solved a problem I was having running a shell command in a Ruby Sidekiq worker process.
The worker needed to:
- cd into a directory
- load an RVM environment
- execute some Ruby scripts, like
bundle
- work
I didn’t realize that subshells executed from Ruby using methods like
system
or Open3
would inherit the Ruby process’s environment.
Environment variables like BUNDLE_GEMFILE
, rvm_path
and GEM_HOME
were already set, causing bundle install
to throw errors like
“Package xyz not found in any sources.”
So, if you want to run shell commands from a Ruby process without
the environment variables that were set in the parent process, use
env
.
env
env
allows you to customize the environment of a shell command. If
you want to ignore all currently set environment variables in a bash
subshell, use the -i
switch:
$ env -i bash --noprofile -lc echo $HOME
It should have no output since $HOME is unset.
A new environment can be set up by prepending environment variables to the command. Here is an example of setting up a fresh RVM environment in a bash subshell:
env -i HOME=/home/thrashroy PATH=/bin:/sbin:/usr/bin:/usr/sbin \
bash -lc 'cd /home/thrashroy/my_app && . /etc/profile.d/rvm.sh \
&& rvm reload && bundle install'