Search and delete files older than “N” days1 min read

Devops Engineer
Sorry! The Author has not filled his profile.
follow me

Lets see how we can  search specific  files or directory which was created “N” days before and delete.

For example find files older than 60 days,

 

## files only ##
find /path/to/dir/ -type f -mtime +60 -ls

## dirs only ##
find /path/to/dir/ -type d -mtime +60 -ls

Replace the ls with -delete to remove files. Be careful, as you might end up deleting important files.  Always keep backups. Always run -ls option first to check about files.
You have been warned.

find /path/to/dir/ -type f -mtime +60 -delete

How to ask for confirm before deleting


find /path/to/dir/ -type f -mtime +60 -exec /bin/rm -i {} \;

Explanation

  1. find : Find command
  2. /path/to/dir/ : Directory path to search
  3. -type f : Only works on files. (the -type d option only works on dirs)
  4. -mtime +60 : Select file with modification time older than 60 days
  5. -exec /bin/rm -i {} \; : Delete file with confirmation
  6. -delete – Delete file
  7. -ls : list file

© 2020, Techrunnr. All rights reserved.

#1
#2
#3
Questions Answered
Articles Written
Overall Points

Related posts

Leave a Reply