I have a one line script which works fine but...

find $HOME/html/mydir/downloads/sec/*.zip  -mtime 2 -exec rm {} \;

It generates an error if there are no files found and my web host then sends me a pointless email. So I want to suppress the error message if the 'error' is "No such file or directory"

I was thinking I could do something like this:

find $HOME/html/mydir/downloads/sec/*.zip 2>&1 | grep -v "No such file or directory" 

...but I don't know how to combine this with my current script such that the output of find will still go to exec if there -are- files found (or if there is another type of error).

  • John1024's answer is basically correct, but an alternative is to check if any files match the mask with something like if echo DirPath/*.zip|grep -q '\*'; then echo No files; else find ... ; fi. Note that the error message is generated if no files match the mask: if files exist their age will determine whether any are then found. – AFH May 14 '16 at 23:32
  • 1
    @AFH: That would fail in the (unlikely) case that there are file(s) whose name(s) contain literal asterisk(s). – G-Man Says 'Reinstate Monica' May 15 '16 at 2:36
  • @G-Man - Quite right. I did actually think of that, but after checking a few things I forgot to mention it. – AFH May 15 '16 at 11:23


find $HOME/html/mydir/downloads/sec/ -maxdepth 1 -name '*.zip' -mtime 2 -delete

find does not have a problem if a search turns up finds no files. It does have a problem if the directory/files that you specify on the command line do not exist. The solution, as shown above, is to specify a directory that exists and ask it to search for .zip files.

Also, note that -exec rm {} \; can be replaced with -delete.

By the way, -mtime 2 will only be true for files that are (rounded to an integer) 2 days old. If you want to delete files that are more than two days olds, then use -mtime +2.

| improve this answer | |
  • A good answer, but I would add -maxdepth 1 in case there are further subdirectories containing zip files, as without this clause more files would be returned than the original command. – AFH May 14 '16 at 23:20
  • @AFH Good point. Answer updated to use -maxdepth 1. – John1024 May 14 '16 at 23:32
  • @John1024: Question: you have the -name parameter twice in your answer. Is that intentional or a typo? – jchwebdev May 15 '16 at 0:16
  • @jchwebdev Yes, that was a typo. Thanks! Answer updated. – John1024 May 15 '16 at 0:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.