How does “(head; tail) < file” work?

前端 未结 4 849
攒了一身酷
攒了一身酷 2020-12-25 12:30

(via https://stackoverflow.com/a/8624829/23582)

How does (head; tail) < file work? Note that cat file | (head;tail) doesn\'t.

Al

4条回答
  •  眼角桃花
    2020-12-25 13:00

    All of these should work as expected if the file is sufficiently large. The head command will consume a certain amount of the input (not just what it needs as it buffers it's input) and if that doesn't leave enough input for the tail command, it won't work.

    Another concern is that the pipe results in both sides executing in parallel and so the producing side might cause the consuming side's head command to read a different amount every time it is run.

    Compare multiple runs of the following command:

    for i in `seq 1 10`; do echo "foo"; done | (head -n1; wc -l)
    

    The wc command should see a different amount of the file every time.

    When using a < to provide input it doesn't seem like this parallelism exists (presumably bash reads the whole input then passes it to the head command).

提交回复
热议问题