Only find first few matched files using find?

You could pipe the output of find through head:

find . -name '*.txt' | head -n 3

This other answer is somewhat flawed. The command is

find . -name '*.txt' | head -n 3

Then there's an explanation in one of the comments [emphasis mine]:

head starts up and waits for input from the lefthand side of the pipe. Then find starts up and searches for files that match the criteria specified, sending its output through the pipe. When head has received and printed the number of lines requested, it terminates, closing the pipe. find notices the closed pipe and it also terminates. Simple, elegant and efficient.

This is almost true.

The problem is find notices the closed pipe only when it tries to write to it – in this case it's when the 4th match is found. But if there's no 4th match then find will continue. Your shell will wait! If it happens in a script, the script will wait, despite the fact we already know the pipe output is final and nothing can be added to it. Not so efficient.

The effect is negligible if this particular find finishes fast by itself but with complex search in a large file tree the command may unnecessarily delay whatever you want to do next.

The not-so-perfect solution is to run

( find … & ) | head -n 3

This way when head exits, the shell continues immediately. Background find process may be ignored then (it will exit sooner or later) or targeted with pkill or something.


To prove the concept you may search for /. We expect one match only, yet find looks for it everywhere and it may take a lot of time.

find / -wholename / 2>/dev/null | head -n 1

Terminate it with Ctrl+C as soon as you see the issue. Now compare:

pidof find ; ( find / -wholename / 2>/dev/null & ) | head -n 1 ; pidof find

Tags:

Find