Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux head utility reading only one line needs more input to exit

Tags:

linux

bash

I need to read from a continuous data stream (pipe, actually), line by line, and I need to exit after the 1st line. RIGHT after the 1st line. Sounded pretty easy but, using "head -n 1", I noticed that I actually need to enter a second line before head exits.

Test case:

[s@svr1 ~]$ cat | head -n 1    
123    <- I type this first (followed by enter, of course)
123    <- I get this output from head, but the command does no exit
456    <- Then I need to type this for the command to exit and bring me back to the prompt
[s@svr1 ~]$

Can someone explain (first and foremost) why it's acting like that, and maybe how I could get what I need? (and I want to stick to basic Linux/Unix lightweight building blocks. No Perl, Python and such...)

Thanks

like image 626
SClark Avatar asked Nov 23 '12 22:11

SClark


1 Answers

Because you're using cat | head -n 1, which is a useless use of cat and not the same as head -n 1. If you do head -n 1 at the console you get the behavior you want — head reads one line, prints it, and exits.

If you do cat | head -n 1, then this happens:

  1. cat reads "123" from its input.
  2. cat writes "123" to its output.
  3. head reads "123" from its input (which is connected to cat's output).
  4. head writes "123" to its output and exits.
  5. cat reads "456" from its input.
  6. cat tries to write "456" to its output.
  7. cat gets SIGPIPE because the process on the other side of its output has died.
  8. cat exits.

cat begins another read as soon as it's written "123" to head, and it doesn't find out that head has died until it tries to write a second line to it.

like image 125
hobbs Avatar answered Oct 25 '22 03:10

hobbs