How do you pipe output from a Ruby script to 'head' without getting a broken pipe error

Posted by dan on Stack Overflow See other posts from Stack Overflow or by dan
Published on 2010-05-16T21:14:46Z Indexed on 2010/05/16 21:20 UTC
Read the original article Hit count: 231

Filed under:
|
|

I have a simple Ruby script that looks like this

require 'csv'
while line = STDIN.gets
  array = CSV.parse_line(line)
  puts array[2]
end

But when I try using this script in a Unix pipeline like this, I get 10 lines of output, followed by an error:

ruby lib/myscript.rb < data.csv  | head

12080450
12080451
12080517
12081046
12081048
12081050
12081051
12081052
12081054
lib/myscript.rb:4:in `write': Broken pipe - <STDOUT> (Errno::EPIPE)

Is there a way to write the Ruby script in a way that prevents the broken pipe exception from being raised?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about unix