How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?
相关问题
- How to get the return code of a shell script in lu
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- Invoking Mirth Connect CLI with Powershell script
相关文章
- 使用2台跳板机的情况下如何使用scp传文件
- In IntelliJ IDEA, how can I create a key binding t
- Ruby using wrong version of openssl
- shell中反引号 `` 赋值变量问题
- How get the time in milliseconds in FreeBSD?
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
Here's a flowchart based on this answer. See also, using
script
to emulate a terminal.Here's a cool one that I use in a ruby script on OS X (so that I can start a script and get an update even after toggling away from the window):
I'm definitely not a Ruby expert, but I'll give it a shot:
You should also be able to do things like:
The answers above are already quite great, but I really want to share the following summary article: "6 Ways to Run Shell Commands in Ruby"
Basically, it tells us:
Kernel#exec
:system
and$?
:Backticks (`):
IO#popen
:Open3#popen3
-- stdlib:Open4#popen4
-- a gem:If you have a more complex case than the common case (that can not be handled with
``
) then check outKernel.spawn()
here. This seems to be the most generic/full-featured provided by stock Ruby to execute external commands.E.g. you can use it to:
Official ruby documentation has good enough examples.
Given a command eg attrib
I've found that while this method isn't as memorable as e.g. system("thecommand") or thecommand in backticks, a good thing about this method compared to other methods.. is e.g. backticks doesn't seem to let me 'puts' the command I run / store the command I want to run in a variable, and system("thecommand") doesn't seem to let me get the output. Whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.
https://blog.bigbinary.com/2012/10/18/backtick-system-exec-in-ruby.html
http://ruby-doc.org/stdlib-2.4.1/libdoc/open3/rdoc/Open3.html