LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Find command returning success even when no files are found (https://www.linuxquestions.org/questions/linux-newbie-8/find-command-returning-success-even-when-no-files-are-found-4175476912/)

LarryBear 09-12-2013 04:17 PM

Find command returning success even when no files are found
 
I've tested this on RHEL/OUL V5.7 and V6.2 with the same results. I need to search a directory for any files older than 25 hours and then do things with those files.

First case: there are no files named *.xmlx and find returns a 1 correctly
# find /mydir/*.xmlx -mmin +1500
find: /mydir/*.xmlx: No such file or directory
# echo $?
1

Second case: there are files named *.xml but none meet the mmin requirement yet find returns a 0 instead of a 1 as I was expecting
# find /mydir/*.xml -mmin +1500
# echo $?
0

This is messing up my scripting and I'm not figuring a way out.

Firerat 09-12-2013 04:54 PM

find was returning 1 because you gave it a none existing file/dir

it doesn’t return an error simply because your nothing matches your criteria


what is it you want to do with the 'found' files?

you could pass to while read, and operate on them

dumb example..
Code:

find /mydir/*.xml -mmin +1500 | while read file;do
  echo "${file}"
  mv "${file}" "${file}.backup"
done


colucix 09-12-2013 04:58 PM

From man find:
Quote:

find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find.
In the first case an error occurs since the search path is not found. On the other hand the command
Code:

find /mydir -name \*.xmlx -mmin +1500
would have returned an exit status of 0. This means that the exit status is not related to the results of the find command, but to the occurrence of errors that find might encounter while performing the search. Said that, you have to check something different from the exit status, for example the number of items found or you can simply do a loop over the find results. In this case, no results means no actions taken:
Code:

while read file
do
  echo $file
done < <(find /mydir -name \*xmlx -mmin +1500)

Hope this helps.


All times are GMT -5. The time now is 02:47 AM.