Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Is there a way to force the find command to stop right after finding the first match?

share|improve this question
add comment

2 Answers

up vote 23 down vote accepted

With GNU find, you can use the -quit predicate:

find . ... -print -quit

If all you do is printing the name, and assuming the filenames don't contain newline characters, you could do:

find . ... -print | head -n 1

That will not stop find after the first match, but possibly, depending on timing upon the second match or later. Basically, find will be terminated with a SIGPIPE when it tries to output something while head is already gone because it has already read and displayed the first line of input.

If you're doing more than printing the paths of the found files, you could try this approach:

find . ... -exec bash -c 'printf "%s\n" "$1"; kill "$PPID"' bash {} \;

(replace printf with whatever you would be doing with that file).

That has the side effect of find returning an exit status reflecting the fact that it was killed though.

Actually, using the SIGPIPE signal instead of SIGTERM (kill -s PIPE instead of kill) will cause some shells to be more silent about that death (but would still return a non-zero exit status).

share|improve this answer
add comment

For entertainment purposes, here's a lazy find generator in Bash. This example generates a ring over the files in the current directory. Read however many you want then kill %+ (maybe just 1)

#!/usr/bin/env bash
unset -v files n
trap 'kill "$x_PID"' EXIT

coproc x while :; do
    find . -type f -maxdepth 1 -exec sh -c "$(</dev/fd/3)" _ {} +
done 4<&0 <<\EOF 3<&0 <&4-
for x; do
    read -r _
    printf '%s\0' "$x"
done
EOF

while
    echo >&${x[1]}
    IFS= read -rd '' -u "$x" 'files[n++]'
do
    printf '%q ' "${files[@]}"
    echo
    sleep .2
done
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.