2

As we know, to remove files we can use this safe option

  find /path/to/directory/ -mindepth 1 -mtime +5 -delete

What if we want to remove both folders and files under /path/to/directory/ folder; what should be the syntax?

The delete option can't remove folders that are not empty.

 find /var/tmp -type d -mindepth 1 -mtime +5 -delete
 find: warning: you have specified the -mindepth option after a non-option    argument -type, but options are not positional (-mindepth affects tests   specified before it as well as those specified after it).  Please specify  options before other arguments.

 find: cannot delete `/var/tmp/foreman-ssh-cmd-1b987fef-10ca-4204-bf4b-441f28a3db07': Directory not empty
 find: cannot delete `/var/tmp/foreman-ssh-cmd-2687d337-2b60-4f20-b581-a70807c22cb9': Directory not empty
 find: cannot delete `/var/tmp/foreman-ssh-cmd-faedbb3a-7756-4c96-8a40-a4a2001b5fb3': Directory not empty
3

You have not used any -type option, so find will remove (-delete) everything that is matched by conditions provided (precisely -mindepth 1 -mtime +5 here), whether it is file or directory (if empty) or anything else.

If you want to remove empty directories only:

find /path/to/directory/ -mindepth 1 -type d -mtime +5 -delete

Just to note, it is better to have a look at the files to be removed before actually doing the removal, drop the -delete:

find /path/to/directory/ -mindepth 1-type d -mtime +5

For the sake of completeness, if you want to search for only files and directories, insert an OR construct in find:

find /path/to/directory/ -mindepth 1 \( -type f -o -type d \) -mtime +5 

If you want to remove the directories that are not empty as well, use rm inside the -exec action:

find /path/to/directory/ -mindepth 1 \( -type f -o -type d \) -mtime +5 -exec rm -r {} +

Add -f with rm if needed.

  • can we remove the option - -mindepth 1 , and what this option mean ? – yael Jan 17 '17 at 6:27
  • @yael You should not remove that, otherwise the $PWD will be matched (current directory: .), -mindepth 1 prevents that. – heemayl Jan 17 '17 at 6:28
  • see my update the delete option cant remove folder that not empty , how to resolve this – yael Jan 17 '17 at 6:40
  • @yael Check my edits. – heemayl Jan 17 '17 at 6:44
  • 1
    @F.Hauri I didn't say anything about that. Note that the question you linked to concerns comments in response to an answer, not comments in response to a comment. On Unix.SE we commonly respond to comments with a comment, not just a comment upvote, in particular so that the commenter is notified. – Stephen Kitt Jan 17 '17 at 7:42

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.