Exit Status Of Find Command

Hello All,
I am trying to capture the exit status of find command and want to delete the files only when it is successful. But it is always returning me as success even if the pattern of that file doesn't exist in the current directory. please help, checked manual page but couldn't able to figure out.

#!/bin/bash -x
logit()
{
 echo "[${USER}][`date`] - ${*}" >> ${LOG_FILE}
}

LOG_FILE=/home/infrmtca/bin/findtest.log


if  find . -type f -name "*xyz*"
then
        logit "Success"
        find . -type f -name "*xyz*" -delete
else
        logit "Failure"
fi
[infrmtca][Mon Jun  3 10:18:10 EDT 2013] - Success

Tried this statement as well but it is always 0.

find . -type f -name "*xyz*" -exec ls {} \;

Thank you.

That is expected behavior of find command.

It returns 0 if all path operands were traversed successfully.

It returns a non-zero exit status only if there is an error occurred.

Instead of the exit status you can check if the list returned is empty.

if [ ! -z $(find . -type f -name "*xyz*") ]
then
        logit "Success"
        find . -type f -name "*xyz*" -delete
else
        logit "Failure"
fi

Thank you. May i please know how does the $ help in this operation? does it makes/converts the output of the find command to string?

And i guess the backslash is to escape/ignore the next subsequent character.

if [ ! -z "$(find . -type f -name \"*xyz*\")" ]

Running find twice assuming that the hierarchy hasn't changed is a bad idea.

It would be a much better solution to delete the files when first encountered, while also printing them to a logfile. Afterwards, the emptiness of the logfile can be tested to determine if any files and were removed.

Alternatively, you can run find and collect matching filenames in a file. Test that file for emptiness. If not empty, rm each file listed.

Regards,
Alister

Indeed one needs "quotes" around the $( ) subcommand,
but \" is problematic; in this case one can use ' instead.

if [ -n "$(find . -type f -name '*')" ]
then

Usually I prefer

if find . -type f -name '*' | grep . >/dev/null
then

You don't need to escape the quotes inside the $(...) command substitution expansion. That is one HUGE advantage of $(...) over `...`.

if [ ! -z "$(find . -type f -name "*xyz*")" ]

will work just fine.