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

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


head is closing the standard output stream after it has read all the data it needs. You should handle the exception and stop writing to standard output. The following code will abort the loop once standard output has been closed:

while line = STDIN.gets  array = CSV.parse_line(line)  begin    puts array[2]  rescue Errno::EPIPE    break  endend


The trick I use is to replace head with sed -n 1,10p.

This keeps the pipe open so ruby (or any other program that tests for broken pipes and complains) doesn't get the broken pipe and therefore doesn't complain. Choose the value you want for the number of lines.

Clearly, this is not attempting to modify your Ruby script. There almost certainly is a way to do it in the Ruby code. However, the 'sed instead of head' technique works even where you don't have the option of modifying the program that generates the message.