How do I source environment variables for a command shell in a Ruby script?

后端 未结 5 1670
野趣味
野趣味 2021-01-01 00:32

I\'m trying to run some third party bash scripts from within my ruby program.

Before I can run them they require me to source a file. On the command line it all wor

相关标签:
5条回答
  • 2021-01-01 00:43

    I did this because I didn't want to have to write a file or mix up my ruby code with this stuff:

    #!/usr/bin/env bash
    eval $(echo "$(cat .env) $1" | tr '\n' ' ')
    

    I put this in ~/bin/run_with_env.sh and then for example I can run:

    % run_with_env.sh "rails console"
    
    0 讨论(0)
  • 2021-01-01 00:51

    I'm not sure if I understand your question correctly. Do you try to source a shell script before running another one? In this case the answer is simple:

    #!/bin/env ruby
    system "source <path_to_source_file> && <command>"
    

    If the source file contains variables which your command should use you have to export them. It is also possible to set environment variables within your Ruby script by using ENV['<name_of_var>'] = <value>.


    Update: Jan 26, 2010 - 15:10

    You can use IO.popen to open a new shell:

    IO.popen("/bin/bash", "w") do |shell|
      shell.puts "source <path_to_source_file>"
      shell.puts "<command>"
    end
    
    0 讨论(0)
  • 2021-01-01 00:55

    Modifying ENV works only for a single thread and I do the below instead. But a question I have how do I use a merged COPY of the environment with IO.popen ? somehow it doesn't seem to work.

    with "system" I can do:

    # ... create new "path" here
    
        subEnv = Hash.new;
        subEnv.merge!(ENV); # copy old environment
        subEnv['PATH'] = path; # set new values in copy
    
        system(subEnv, commandLine);
    
    0 讨论(0)
  • 2021-01-01 01:00

    Do this:

    $ source whatever.sh
    $ set > variables.txt
    

    And then in Ruby:

    File.readlines("variables.txt").each do |line|
      values = line.split("=")
      ENV[values[0]] = values[1]
    end
    

    After you've ran this, your environment should be good to go.

    0 讨论(0)
  • 2021-01-01 01:00

    This is horrible, but..

    env = %x{. /some/shell/script/which/setups/your/env && env}
    env.split("\n").each do |line|
      key, value = line.split("=", 2)
      ENV[key] ||= value unless value.nil? or value.empty?
    end
    
    0 讨论(0)
提交回复
热议问题