1832273 Members
2039 Online
110041 Solutions
New Discussion

Execute "find" only once

 
SOLVED
Go to solution
MohitAnchlia
Frequent Advisor

Execute "find" only once

Here is my scenario: I could have 1M files in a directory. I need to report that there are more than 0 files in that directory. Basically, I don't want to parse through all the files. I want to quit as soon as I hit first file. I was trying to do the following:

for i in `find . -name "*.bin"`
do
echo $i
#exit after first occurrence.
exit
done

I think in above example, find will only return after it's done parsing through all the files. I need to find out some command that will exit after one try and doesn't parse through the entire directory.

I also tried following but didn't work:
for i in `find . -name "*.bin" -exec exit \;`
do
exit
done
3 REPLIES 3
Sandman!
Honored Contributor

Re: Execute "find" only once

# ls -1 *.bin | wc -l > /dev/null && exit
James R. Ferguson
Acclaimed Contributor

Re: Execute "find" only once

Hi:

If you want to consider only files in a directory (without recursively descending any subdirectories), use 'ls' and skip the "total" line and the '.' and '..' directories that a root user will return, but include "hidden" files beginning with a ".". Capture the file count and compare as you please:

# ls -al /path|awk '!/^total/ && $1~/^-/ && $NF !~/^\.\.?$/'|wc -l

Regards!

...JRF...

Steven Schweda
Honored Contributor
Solution

Re: Execute "find" only once

This seems to be crude but effective:

dy # cat /misc/kill_parent.sh
#!/bin/sh
kill $PPID
dy # find /usr -name 'n*' -exec echo {} \; -exec /misc/kill_parent.sh \;
/usr/bin/netstat
Terminated
dy #


> I could have 1M files in a directory.

Some might say that this is not a sign of a
good design.