sonoluminescence
sonoluminescence

Reputation: 1012

How to pass shell script variables back to ruby?

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

Upvotes: 1

Views: 1053

Answers (2)

user1934428
user1934428

Reputation: 22227

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.

Upvotes: 1

peak
peak

Reputation: 116770

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

Upvotes: 2

Related Questions