How to get the exit code of -exec in the find command

Hi

I have a little problem with the find command in a script that I'm writing. The script should check if there are some files younger than 100 seconds and then syncronise them with rsync.

My find command:

find -type f -cmin -100 -exec rsync -a --delete directory1/ directory2/

When I check the exit code with $? I always get 0 even if I can be sure the rsync should fail. How can I get the exit code of the rsync and the find?

I allready contacted the man page but it didn't really helped me much.

-cmin -100 is mean less than 100 minutes, not 100 seconds.

find with -exec will be used as below format, but I don't see the part of {} \; in your script.

find . -exec ls -l {} \;

Yes 100 mins is correct.

Does this part make any difference? The command itself works that I know. But when I try to make it fail, I don't get another exit code.

---------- Post updated at 01:53 PM ---------- Previous update was at 10:11 AM ----------

What I have tried so far:

It came up in my mind, that this could work like a pipe. I found an information, that the exitcode of the first command in a pipe could get read (in a bash) by {$PIPESTATUS[0]}, the second command of the pipe by {$PIPESTATUS} and so on. But unfortunately it doesn't work in that case... :frowning:

I think it might be easier to run find and then store the results in a temporary file, then run a script to read the file and execute your rsync command.

You can easily get the exit code of rsync that way.

Instead of using -exec, try using &&.

$ find . -cmin -100 -type f && rsync -a --delete directory1/ directory2/

You could try and work find's internal boolean logic, eg.

find -type f -cmin -100 \( -exec rsync -a --delete directory1/ directory2/ \; -o -exec echo {} failed \; \)

Thank you for your posts.

@Neo: that would be slower (i know not much but it need to be fast and slim)
@agn: thx will try that right now
@pludi: didn't know that this option exists, I'll try that too

Don't forget about error handling and logging :smiley:

Ok I have tried that but how do I get the exit status back? I tried it with $? $! and the PIPESTAUS

find -type f -cmin 100 && cat /var/log/messages|wc -l

PS: I took the cat command on the messages file because that should give me for sure the exitstatus 1 back.

---------- Post updated at 04:06 PM ---------- Previous update was at 02:45 PM ----------

Thank you again for all your help!

I think I'm going to use the version pludi has posted. So far it is just modified on my test environment but hopefully I'm able to test it tomorrow on a real system (with bit more than 10 files and other userrights).

My solution (based on pludi's idea)

find . -type f -cmin 100 \( -exec rsync -a --delete {}/ directory2/{} \; -o -exec echo {} > failed.log \; \)

The good thing about that solution is, that I have the failed files written in a log.