Calling shell commands from Ruby

2018-12-31 04:48发布

How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?

20条回答
骚的不知所云
2楼-- · 2018-12-31 04:53

One more option:

When you:

  • need stderr as well as stdout
  • can't/won't use Open3/Open4 (they throw exceptions in NetBeans on my Mac, no idea why)

You can use shell redirection:

puts %x[cat bogus.txt].inspect
  => ""

puts %x[cat bogus.txt 2>&1].inspect
  => "cat: bogus.txt: No such file or directory\n"

The 2>&1 syntax works across Linux, Mac and Windows since the early days of MS-DOS.

查看更多
路过你的时光
3楼-- · 2018-12-31 04:53

Not really an answer but maybe someone will find this useful, and its regarding to this.

When using TK GUI on Windows, and u need to call shell commands from rubyw, u will always have an annoying cmd window popping up for less then a sec.

To avoid this u can use

WIN32OLE.new('Shell.Application').ShellExecute('ipconfig > log.txt','','','open',0)

or

WIN32OLE.new('WScript.Shell').Run('ipconfig > log.txt',0,0)

Both will store ipconfig's output inside 'log.txt', but no windows will come up.

U will need to require 'win32ole' inside your script.

system(), exec() and spawn() will all pop up that annoying window when using TK and rubyw.

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 04:55

We can achieve it in multiple ways.

Using Kernel#exec, nothing after this command is executed:

exec('ls ~')

Using backticks or %x

`ls ~`
=> "Applications\nDesktop\nDocuments"
%x(ls ~)
=> "Applications\nDesktop\nDocuments"

Using Kernel#system command, returns true if successful, false if unsuccessful and returns nil if command execution fails:

system('ls ~')
=> true
查看更多
与风俱净
5楼-- · 2018-12-31 04:56

Some things to think about when choosing between these mechanisms are:

  1. Do you just want stdout or do you need stderr as well? or even separated out?
  2. How big is your output? Do you want to hold the entire result in memory?
  3. Do you want to read some of your output while the subprocess is still running?
  4. Do you need result codes?
  5. Do you need a ruby object that represents the process and lets you kill it on demand?

You may need anything from simple backticks (``), system(), and IO.popen to full-blown Kernel.fork/Kernel.exec with IO.pipe and IO.select.

You may also want to throw timeouts into the mix if a subprocess takes too long to execute.

Unfortunately, it very much depends.

查看更多
冷夜・残月
6楼-- · 2018-12-31 04:57

This explanation is based on a commented Ruby script from a friend of mine. If you want to improve the script, feel free to update it at the link.

First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems.

Here are ways to execute a shell script:

cmd = "echo 'hi'" # Sample string that can be used
  1. Kernel#` , commonly called backticks – `cmd`

    This is like many other languages, including Bash, PHP, and Perl.

    Returns the result of the shell command.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-60

    value = `echo 'hi'`
    value = `#{cmd}`
    
  2. Built-in syntax, %x( cmd )

    Following the x character is a delimiter, which can be any character. If the delimiter is one of the characters (, [, {, or <, the literal consists of the characters up to the matching closing delimiter, taking account of nested delimiter pairs. For all other delimiters, the literal comprises the characters up to the next occurrence of the delimiter character. String interpolation #{ ... } is allowed.

    Returns the result of the shell command, just like the backticks.

    Docs: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html

    value = %x( echo 'hi' )
    value = %x[ #{cmd} ]
    
  3. Kernel#system

    Executes the given command in a subshell.

    Returns true if the command was found and ran successfully, false otherwise.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-system

    wasGood = system( "echo 'hi'" )
    wasGood = system( cmd )
    
  4. Kernel#exec

    Replaces the current process by running the given external command.

    Returns none, the current process is replaced and never continues.

    Docs: http://ruby-doc.org/core/Kernel.html#method-i-exec

    exec( "echo 'hi'" )
    exec( cmd ) # Note: this will never be reached because of the line above
    

Here's some extra advice: $?, which is the same as $CHILD_STATUS, accesses the status of the last system executed command if you use the backticks, system() or %x{}. You can then access the exitstatus and pid properties:

$?.exitstatus

For more reading see:

查看更多
无与为乐者.
7楼-- · 2018-12-31 04:58
  • backticks ` method is the easiest one to call shell commands from ruby. It returns the result of the shell command.

     url_request = 'http://google.com'
     result_of_shell_command = `curl #{url_request}`
    
查看更多
登录 后发表回答