find command return true if a file was found
Hello there,
Anyone knows how to manage the find command to return true or false if a file was found/or not? I tried to man find but didn't found anything. Regards, |
Hi,
the find command will only return non zero value on error, so it will return 0 if it find or not file. A solution could be to pipe the output to grep -q who will return non zero if not found. Something like that : Code:
find . -name 'filename' | grep -q filename && echo "File found" || echo "File not found" Solution 2: Code:
[ -n "$(find . -name 'filename' 2>/dev/null)" ] && echo "File found" || echo "File not found" |
The return value of find ./ -name does_not_exist = 0; Also find ./ -name does_exist returns 0.
So, what can you do? Code:
if [ $(find ./ -name does_exist | wc -l) -gt 0 ] Edit: The solution looks different, but is essentially the same; Chirel beat me to it ;-) |
I recommend using a short-circuited version of Chirel's solution:
Code:
FILE=`find . -name 'filename' -print -quit` |
Code:
if [ "$(find -option1 -option2)" '!=' '' ] |
case is more efficient than [ or test when you can get by with simple pattern matches.
Code:
case `find . -name 'filename' -print -quit` in |
Quote:
Code:
time bash -c 'for F in `seq 1 10000` ; do true ; done' |
Quote:
|
Quote:
Code:
strace -f -F bash -c '[ -e somefile ] && echo "somefile exists" || echo "somefile does not exist"' Code:
strace -f -F bash -c '/usr/bin/[ -e somefile ] && echo "somefile exists" || echo "somefile does not exist"' |
Sure, `type test` or `type [` will tell you that the internals are being used. I discovered that case was faster when I tried to optimize some really slow code where I was using brackets in multi-choice if-elif-then pattern comparisons. In my routine 'case' ran in about 30% of the time as using brackets. In the OP's example, the difference would probably less.
|
Hi,
Fun to see where a simple question can bring a post :) I must admit that the Nominal Animal find . -name 'filename' -print -quit is really nice. No subcall to grep et no full tree traversal if the file is found in the begining . . . Good one. |
Hei you gurus ,
my issue is that on solaris -quite doesn't work. any workaround for this? :( thx |
Quote:
Code:
FILE=`find . -name 'filename' -print -exec sh -c 'kill -TERM $PPID' ';'` |
All times are GMT -5. The time now is 08:47 AM. |