17

How easy is it to hide results from system commands in ruby? For example, some of my scripts run

system "curl ..." 

and I would not prefer to see the results of the download.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
dejay
  • 758
  • 2
  • 6
  • 18
  • 3
    Note that curl already has a `--silent` mode you can use. – Phrogz Jun 06 '12 at 23:08
  • possible duplicate of [Suppressing the output of a command run using 'system' method while running it in a ruby script](http://stackoverflow.com/questions/1960838/suppressing-the-output-of-a-command-run-using-system-method-while-running-it-i) – Ciro Santilli OurBigBook.com Oct 17 '14 at 19:59

4 Answers4

16

To keep it working with system without modifying your command:

system('curl ...', :err => File::NULL)

Source

noraj
  • 3,964
  • 1
  • 30
  • 38
11

You can use the more sophisticated popen3 to have control over STDIN, STDOUT and STDERR separately if you like:

Open3.popen3("curl...") do |stdin, stdout, stderr, thread|
  # ...
end

If you want to silence certain streams you can ignore them, or if it's important to redirect or interpret that output, you still have that available.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 3
    You may need to "require 'open3'". Use "myvarname = stdin.read" if you want to process output. – DanielaWaranie Nov 20 '14 at 03:11
  • To use advanced outputs like stdin, stderr etc. it's okay, but just to get the output of the console it's a dependency which can be eliminated with e.g. `%x{bash-command arg1 arg2}` – siegy22 May 12 '16 at 11:41
  • 1
    @RaVeN One advantage of `popen3` or `system` is you can properly break out arguments: `system("example", "--file", user_supplied_filename)` is safe from shell injection. `system("example --file #{user_supplied_filename}")` is **extremely dangerous** and should not be done. – tadman May 12 '16 at 16:23
5

Easiest ways other than popen:

  1. Use %x instead of system. It will automatically pipe

    rval = %x{curl ...}       #rval will contain the output instead of function return value
    
  2. Manually pipe to /dev/null. Working in UNIX like system, not Windows

    system "curl ... > /dev/null"
    
SwiftMango
  • 15,092
  • 13
  • 71
  • 136
2

The simplest one is to redirect stdout :)

system "curl ... 1>/dev/null"
# same as
`curl ... 1>/dev/null`
fl00r
  • 82,987
  • 33
  • 217
  • 237