2

my backups are stored in folders. e.g

 **05092013** > 
 - File1.sql
 - File2.sql
 - File1.tar
 - File2.tar

and so on.

Now I want to delete all Folders that are older than X Days.

I tried this

find $FILEDIR -mtime +14 -exec rm {} \;

but it only deletes all files and not the folders. how can i delete all files and folders that are older?

can someone help me?

Thx in advance cSGermany

jww
  • 97,681
  • 90
  • 411
  • 885
invictus
  • 825
  • 1
  • 9
  • 33

2 Answers2

4

Use -r?

find "$FILEDIR" -mtime +14 -exec rm -ir {} \;

Change -ir to just -r if you know what you're doing.

Or use -delete:

find "$FILEDIR" -mtime +14 -delete

But please, please make sure you know what you're doing.

You could add checks like this too to make sure $FILEDIR is always somewhere in your home directory:

[[ $FILEDIR == /home/abc/* ]] && find "$FILEDIR" -mtime +14 -delete
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • I don't know exactly what I'm doing ;) This is quite new to me. But it is not possible to delete files which are not in the FILEDIR directory?! – invictus Sep 05 '13 at 13:14
  • so: find $FILEDIR -type d -mtime +14 -exec rm -r {} \; should work? – invictus Sep 05 '13 at 13:18
  • @cSGermany Add `-mindepth 1`: `[[ $FILEDIR == /home/abc/* ]] && find "$FILEDIR" -mindepth 1 -mtime +14 -delete`. Another option to add checks without using `[[ ]]` is to use `-wholename`: `find "$FILEDIR" -mindepth 1 -wholename '/home/abc/*' -mtime +14 -delete`. – konsolebox Sep 05 '13 at 13:20
1
  • to find only directory, you could add find $FILEDIR -type d ... it could avoid to remove files (e.g. files under your given root dir) by mistake.
  • to remove a non-empty directory, you need rm -r, so -r option is important here.
Kent
  • 189,393
  • 32
  • 233
  • 301