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

1
  • 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. Commented Mar 10, 2016 at 4:50

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I'll give it a try.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.