Exit always returns 0

This returns 0 even when it does not delete any files.

Is it because -print returns 0?

RETVAL=$?
Docs_Backups=/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Documents_Backups/
Scripts_Backups=/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups/

# create some old files
#touch -d 20120101 /media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups/test1
#touch -d 20120101 /media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups/test2
#touch -d 20120101 /media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups/test3
echo "Files older than 3 days."
find $Docs_Backups -mindepth 1 -mtime +3 -print -delete 
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure
find $Scripts_Backups -mindepth 1 -mtime +3 -print -delete 
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure
echo "Files older than 3 days have been deleted."

I can't find an exit in your code snippet. Assuming you run through the entire code, and leave it with the last line shown, it's obvious it returns 0 as the last echo succeeds.

If you ask yourself why your find s always output a success, look at the RETVAL variable: it's set by the exit code of an obscure command run before the entry into your code snippet.

1 Like

find simply doesn't return nonzero unless something prevents it from doing what you asked it to do. If it tries to do open a directory and the system tells it "Permission denied", that's an error for example. "Zero files" on the other hand is not an error, just a fact.

Anyway your use of $RETVAL is wrong, because nothing ever changes it. It remains the same throughout your entire program. Using $? instead would also be wrong, because everything changes it -- every time you run any program or test any condition, that changes the value of $?. Even [ $? -eq 0 ] changes the value of $? afterwards. If you want to do more complicated logic in your shell script, use proper if/then statements, case statements, and the like.

What I might try is something like this:

# Always quote your variables
find "${Docs_Backups}" -mindepth 1 -mtime +3 -print -delete > "/tmp/$$"

if [ -s "/tmp/$$" ]
then
        echo "Found some files"
else
        echo "Found zero files"
fi

rm -f "/tmp/$$"

/tmp/$$ is a simple way of making a random temporary file, since $$ is your process ID and ought to be unique while your program is running.

-s is true when the file has any contents, false when it has no contents.

2 Likes

Thanks for the valuable info.

------ Post updated at 06:50 PM ------

I made a change in my user profile and now I don't like the new look.

I would like to attach a screenshot, but could not find a way.

Thanks.

Please read the FAQ for Forum Usage - Includes Attachments:

You can also attach images by uploading images to your Album.

and the cut and paste the provide IMG tags in the post.