-1

We have a simple scripts that suppose to delete old folders. The problems is that it doesn't delete them recursively.

This is the command:

find $PWD -maxdepth 5 -mtime +80 | xargs -I{} rm -Rvf {}

It removes the files and folders but suddenly tries to remove a file from a directory it already deleted.

The server is running CentOS, and the folders are mounted using NFS from the storage.

What can we do?

gWaldo
  • 11,957
  • 8
  • 42
  • 69
yanivhs
  • 3
  • 1

1 Answers1

2

This happens because the rm receives a list of all the found files and directories from the find command. And directories directories in the list located in front of them and deleted files recursively.

I can offer two solutions:

  1. Sort recursive find results: find $PWD -maxdepth 5 -mtime +80 | sort -r | xargs -I{} rm -Rvf {}
  2. Use -delete option instead of external rm tool. find $PWD -maxdepth 5 -mtime +80 -delete

UPD.1 As sugests @Dimitar you can add -type d then find will operate only with directories. It may be more fast, but in this case you don't cleanup old files in $PWD directory.

find $PWD -maxdepth 5 -mtime +80 -type d | xargs -I{} rm -Rvf {}

UPD.2 As sugests @ezra-s you can do it without xargs:

find $PWD -maxdepth 5 -mtime +80 -exec rm -Rvf {} \;

And I'm think this is really best way.

Slipeer
  • 3,295
  • 2
  • 21
  • 33
  • I'll try that too, although -delete didn't worked so well when deleting large amount of files – yanivhs Jan 18 '17 at 13:31
  • Each of these options has its own nuances, so I offered two. – Slipeer Jan 18 '17 at 13:33
  • 1
    there is no need to use xargs, remember you can just `find $PWD -maxdepth 5 -mtime +80 -type d -exec rm -Rvf {} \;` – Daniel Ferradal Jan 18 '17 at 13:44
  • After some testing we used your first solutions : `find $PWD -maxdepth 5 -mtime +80 | sort -r | xargs -I{} rm -Rvf {}` . without the xargs the command sometimes fails. Thanks @Slipeer – yanivhs Jan 22 '17 at 14:33