[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Quit after finding first N files
From: |
James Youngman |
Subject: |
Re: Quit after finding first N files |
Date: |
Fri, 5 Mar 2010 10:09:05 +0000 |
On Thu, Mar 4, 2010 at 2:04 PM, Nexor <address@hidden> wrote:
> Hello,
>
> How would you quit find after finding first X files (matches in general)?
> I've found in the archives the idea to execute an external command
> that could kill the parent.
Yes. I normally choose "head" as that command; piping the output of
find to head -n X will cause head to exit when it's read X lines, and
this results in SIGPIPE being sent to the find process.
> Would you have an idea for a more elegant solution (probably by using -quit
> somehow )?
You could use -quit but the problem is really just a shell programming
problem, it hasn't got much to do with find:
~$ rm -f /tmp/count
~$ find /usr/bin \( -type f -print \) -a \( -exec flock /tmp/count
/tmp/limit.sh /tmp/count 6 \; -o -quit \) 2>/dev/null
/usr/bin/zjsdecode
/usr/bin/git-log
/usr/bin/sdparm
/usr/bin/git-prune-packed
/usr/bin/ncgen
/usr/bin/pktype
~$ cat /tmp/limit.sh
#! /bin/sh
usage_error() {
cat >&2 <<EOF
$@
usage: $0 counter_file limit
EOF
exit 1
}
if [[ "$#" -lt 2 ]]; then
usage_error "not enough arguments"
elif [[ "$#" -gt 2 ]]; then
usage_error "too many arguments"
elif ! [[ "$2" -ge 0 ]]; then
usage_error "limit should be a decimal number"
else
count_file="$1"
limit="$2"
fi
if count_value=$(cat $count_file); then
if [[ -z "$count_value" ]]; then
count_value=1 # Initialise the count at 1.
else
count_value=$(( 1 + $count_value ))
fi
if ! echo "$count_value" >| "$count_file"; then
exit 2 # could not update the counter.
elif [[ "$count_value" -ge "$limit" ]]; then
exit 1 # We reached the limit
fi
else
exit 2 # Unable to read the counter file.
fi
~$ whatis flock
flock (1) - Manage locks from shell scripts
flock (2) - apply or remove an advisory lock on an open file
James.