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
Because you’re using
cat | head -n 1, which is a useless use of cat and not the same ashead -n 1. If you dohead -n 1at the console you get the behavior you want —headreads one line, prints it, and exits.If you do
cat | head -n 1, then this happens:catreads “123” from its input.catwrites “123” to its output.headreads “123” from its input (which is connected tocat‘s output).headwrites “123” to its output and exits.catreads “456” from its input.cattries to write “456” to its output.catgetsSIGPIPEbecause the process on the other side of its output has died.catexits.catbegins another read as soon as it’s written “123” tohead, and it doesn’t find out thatheadhas died until it tries to write a second line to it.