Shell – Using `find` on not existing directory

findshell

Is there a simple way to make this silently do nothing, if /my-directory does not exist?

find /my-directory -type f -mtime +14 -print0 | xargs -r0 rm

Versions:

  • find: GNU findutils 4.5.10
  • bash 4.2.53

Best Answer

You can throw away error reporting from find with 2>/dev/null, or you can avoid running the command at all:

test -d /my-directory && find /my-directory -type f -mtime +14 -print0 | xargs -r0 rm

As a slight optimisation and clearer code, some versions of find - including yours - can perform the rm for you directly:

test -d /my/directory && find /my-directory -type f -mtime +14 -delete