I was just running a few commands in a terminal and I started wondering, does Unix/Linux take shortcuts when running piped commands?
For example, let's say I have a file with one million lines, the first 10 of which contain hello world
. If you run the command grep "hello world" file | head
does the first command stop as soon as it finds 10 lines, or does it continue to search the entire file first?
Best Answer
Sort of. The shell has no idea what the commands you are running will do, it just connects the output of one to the input of the other.
If
grep
finds more than 10 lines that say "hello world" thenhead
will have all 10 lines it wants, and close the pipe. This will causegrep
to be killed with a SIGPIPE, so it does not need to continue scanning a very large file.