Source shell script into environment within a ruby script
environment, ruby, scripting, shell
Solution
The reason this isn't working for you is b/c ruby runs its `system` commands in separate shells. So when one system command finishes, the shell that had sourced your file closes, and any environment variables set in that shell are forgotten.
If you don't know the name of the sourced file until runtime, then Roboprog's answer is a good approach. However, if you know the name of the sourced file ahead of time, you can do a quick hack with the hashbang line.
% echo sourcer.rb
#!/usr/bin/env ruby
exec "csh -c 'source #{ARGV[0]} && /usr/bin/env ruby #{ARGV[1]}'"
% echo my-script.rb
#!/usr/bin/env ruby sourcer.rb /path/to/file/I/want/to/source.csh
puts "HAPPYTIMES = #{ENV['HAPPYTIMES']}"
% ./my-script.rb
HAPPYTIMES = True
All of these will only help you use the set enviroment variables in your ruby script, not set them in your shell (since they're forgotten as soon as the ruby process completes). For that, you're stuck with the `source` command.
Problem
If I'm writing a shell script and I want to "source" some external (c-)shell scripts to set up my environment, I can just make calls like this: ``` source /file/I/want/to/source.csh ``` I want to replace a shell script that does this with a ruby script. Can I do a similar thing in the ruby script? Update: Just tried it with test_script.csh: ``` #!/bin/csh setenv HAPPYTIMES True ``` ...and test_script.rb: ``` #!/usr/bin/env ruby system "~/test_script.csh" system "echo $HAPPYTIMES" ``` Sadly, no HAPPYTIMES as of yet.