Exporting an Environment Variable in Ruby

后端 未结 4 1163
忘掉有多难
忘掉有多难 2020-11-30 03:15

How do I export an environment variable from within a Ruby script to the parent shell? For example, implementing a naïve implementation of the read Bash builtin

4条回答
  •  半阙折子戏
    2020-11-30 03:43

    I just tried this and it looks good.

    cmd = "echo \"FOO is \\\"$FOO\\\"\"";                                
    system(cmd);
    
    # Run some Ruby code (same program) in the child process
    fork do
        puts "In child process. parent pid is #$$"
        ENV['FOO']='foo in sub process';
        system(cmd);
        exit 99
    end
    child_pid = Process.wait
    puts "Child (pid #{child_pid}) terminated with status #{$?.exitstatus}"
    
    system(cmd);
    

    This seems to work well - at least on MacOSX

    I get

    FOO is ""
    In child process. parent pid is 1388
    FOO is "foo in sub process"
    Child (pid 1388) terminated with status 99
    FOO is ""
    

    Seems nice in it restores prior state automatically

    Ok - now tried a different one as this doesn't spawn 2 subprocesses

    Use Process.spawn(env,command)
    
    pid = Process.spawn({ 'FOO'=>'foo in spawned process'}, cmd );
    pid = Process.wait();  
    

    This acts like the C system call and allows you to specify pipes and all that other stuff too.

提交回复
热议问题