1

I have a ruby script executing a shell script. How can I pass shell script data back to the ruby script.

      desc "Runs all the tests"
      lane :test do 

        sh "../somescript.sh"

        print variables_inside_my_script // i want to access my script data here.

      end

I'm able to do the reverse scenario using environment variables from ruby to shell script.

      desc "Runs all the tests"
      lane :test do 

        puts ENV["test"]

        sh "../somescript.sh" // access test using $test

      end

Thanks

sonoluminescence
  • 1,002
  • 1
  • 11
  • 28
  • Not possible. Subprocesses inherit a copy of the parent's environment; they can't affect the parent's environment. If you want to pass data from a shell script to the calling process, the easiest way to do it is through its output. – Amadan Mar 10 '16 at 04:50

2 Answers2

2

It's not so clear what variables_inside_my_script is supposed to mean here, but as a rule operating systems do not allow one to "export" variables from a subshell to the parent, so rubyists often invoke the subcommand with backticks (or equivalent) so that the parent can read the output (stdout) of the subshell, e.g.

output = %x[ ls ]

There are alternative techniques that may be useful depending on what you really need -- see e.g.

  1. Exporting an Environment Variable in Ruby

  2. http://tech.natemurray.com/2007/03/ruby-shell-commands.html

  3. http://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html

Community
  • 1
  • 1
peak
  • 105,803
  • 17
  • 152
  • 177
1

If the shell script is under your control, have the script write the environment definitions in Ruby syntax to STDOUT. Within Ruby, you eval the output:

eval `scriptsettings.sh`

If your script produces other output, write the environment definitions to a temporary file and use the load command to read them.

user1934428
  • 19,864
  • 7
  • 42
  • 87