Linux head utility reading only one line needs more input to exit
bash, linux
Solution
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:
- `cat` reads "123" from its input.
- `cat` writes "123" to its output.
- `head` reads "123" from its input (which is connected to `cat`'s output).
- `head` writes "123" to its output and exits.
- `cat` reads "456" from its input.
- `cat` tries to write "456" to its output.
- `cat` gets `SIGPIPE` because the process on the other side of its output has died.
- `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.
Problem
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