简体   繁体   English

如何将Shell脚本变量传递回ruby?

[英]How to pass shell script variables back to ruby?

I have a ruby script executing a shell script. 我有一个执行shell脚本的ruby脚本。 How can I pass shell script data back to the ruby script. 如何将Shell脚本数据传递回ruby脚本。

      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. 我可以使用从ruby到shell脚本的环境变量来完成相反的情况。

      desc "Runs all the tests"
      lane :test do 

        puts ENV["test"]

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

      end

Thanks 谢谢

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, eg 目前尚不清楚variables_inside_my_script在这里是什么意思,但通常操作系统不允许人们将变量从子shell“导出”到父级,因此红宝石主义者经常使用反引号(或等效符号)调用子命令,以便父级可以读取子shell的输出(stdout),例如

output = %x[ ls ]

There are alternative techniques that may be useful depending on what you really need -- see eg 根据您的实际需求,有些替代技术可能会有用-参见例如

  1. Exporting an Environment Variable in Ruby 在Ruby中导出环境变量

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

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

If the shell script is under your control, have the script write the environment definitions in Ruby syntax to STDOUT. 如果shell脚本在您的控制之下,则让该脚本以Ruby语法将环境定义写入STDOUT。 Within Ruby, you eval the output: 在Ruby中,您可以eval输出:

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. 如果您的脚本产生其他输出,则将环境定义写入临时文件,然后使用load命令读取它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM