Shell out from ruby while setting an environment variable

前端 未结 5 486
囚心锁ツ
囚心锁ツ 2020-12-06 16:04

I need to shell out to a process while setting an environment variable for it. I tried this one-liner:

system \"RBENV_VERSION=system ruby extconf.rb\"


        
相关标签:
5条回答
  • 2020-12-06 16:30

    This may work?

    system <<-CMD
    export VARNAME=123
    other_command
    CMD
    
    0 讨论(0)
  • 2020-12-06 16:34

    Using your same approach, but wrapped up as a block method that temporarily modifies the environment (like the block form of Dir.chdir):

    def with_environment(variables={})
      if block_given?
        old_values = variables.map{ |k,v| [k,ENV[k]] }
        begin
           variables.each{ |k,v| ENV[k] = v }
           result = yield
        ensure
          old_values.each{ |k,v| ENV[k] = v }
        end
        result
      else
        variables.each{ |k,v| ENV[k] = v }
      end
    end
    
    with_environment 'RBENV_VERSION'=>'system' do
      `ruby extconf.rb`
    end
    
    0 讨论(0)
  • 2020-12-06 16:35

    Ruby 1.9 includes Process::spawn which allows an environ hash to be provided.

    Process::spawn is also the foundation for system, exec, popen, etc.
    You can pass an environment to each.

    Under Ruby 1.8, you may want to consider the POSIX::Spawn library,
    which provides the same interfaces

    0 讨论(0)
  • 2020-12-06 16:38
    system({"MYVAR" => "42"}, "echo $MYVAR")
    

    system accepts any arguments that Process.spawn accepts.

    0 讨论(0)
  • 2020-12-06 16:45

    Actually that worked for me.

    shai@comp ~ » irb                                                                                                                                     
    1.9.3p0 :001 > system %{SHAIGUITAR=exists ruby -e 'puts ENV["SHAIGUITAR"]'}
    exists
     => true 
    

    But if it doesn't, maybe you can try prepending "env" to whatever variable you need. E.g.

    system(%{env SHAIGUITAR=exists ruby bla.rb})
    
    0 讨论(0)
提交回复
热议问题