Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm trying to check the existence of several files, without knowing in advance where the files are located. So, I thought of find as the de facto utility to do this... It works as expected, but the problem is that it does not acknowledge the non-existence of files, that is, if a file does not exists under the searched directory then, as you will expect, it's not showed in the results.

I guess this is fine, as the find command is meant to find files, which actually exists in the first place (d'oh). But I wonder if there's a way for the find command to return a message like "File not found" or alike, to inform that the file is not there, instead of failing (or succeeding) silently.

I thought that maybe I could workaround the problem by using find's return code by querying $?, but even when the file is not found the return code is 0.

Just an example of what I have...

find . -name foo.sh 
find . -name bar.sh 

and what it returns in case the only file in there is foo.sh:

./directory/foo.sh

What I would like to receive is:

./directory/foo.sh
bar.sh not found

Does anyone knows of a find flag or any other workaround I can use?
Thanks!

share|improve this question

2 Answers 2

up vote 0 down vote accepted

you could try find . -name foo | grep \/ to set the exit code.

grep looks for any / in the output and returns exit code 1 if none is found

share|improve this answer
    
Genius! I can use: find . -name foo | grep \/ || echo "File not found". Thanks! –  jim May 13 at 15:40

I don't think find has an option to say 'what you looked for was not found'.

You can count the number of lines returned by find and if it's 0 print the 'not found' message. Something like:

#/bin/bash

# put find output to a temp file
find . -name 'foo.sh' > /var/tmp/find.tmp.$$

# count the number of lines
COUNT=`wc -l /var/tmp/find.tmp.$$ | awk '{ print $1 }'`


if [ $COUNT -eq 0 ]
then
   # find didn't return any results, so print message
   echo "foo.sh not found"
else
   # find returned results, print them
   cat /var/tmp/find.tmp.$$
fi
# remove temp file
rm /var/tmp/find.tmp.$$

That will print the output of the find command if there were any results or 'foo.sh not found' when no results found.

share|improve this answer
    
Sounds like a good idea in case you want to create a wrapper for find, but in this case I just wanted a simple one-liner just to be aware that the file is not there. +1 anyway, cause as I said, it's a good idea. Thanks! –  jim May 13 at 15:41

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.