Script to Auto delete files older than a few minutes in ubuntu

17,140

Solution 1

This should do it, I've tested this with *.txt, but you can change it to all files using *.* instead:

#!/bin/bash
cd /usr/local/my_logs
find ./*.txt -type f -mmin +5 -exec rm {} \;

Solution 2

I use a script like this to delete backups older than 30 days:

find "/backups/mysql/" -type f -mtime +30 -print0 | xargs -0 rm -f

Based on that, I think you could do something similar:

find "/yourDir/" -type f -mmin +10 -print0 | xargs -0 rm -f

I think that would get 'em over 10 minutes

Solution 3

This will run forever, delete files modified more than three minutes prior to each iteration and wait one minute before doing it again:

while true
do
    find -type f -mmin +3 -delete
    sleep 60
done

You can add -maxdepth 1 if you don't want it to be recursive.

Share:
17,140

Related videos on Youtube

user684503
Author by

user684503

Updated on September 17, 2022

Comments

  • user684503
    user684503 over 1 year

    is there a shell script out there that deletes all files in a folder that are older than x minutes?

  • Dennis Williamson
    Dennis Williamson about 14 years
    I don't think you can specify the directory and files at the same time in that way.
  • user2661503
    user2661503 about 14 years
    I just change to the target directory and then run that script and it seems to work?
  • Dennis Williamson
    Dennis Williamson about 14 years
    You're right. I keep forgetting that find is a lot less picky than it used to be.
  • user684503
    user684503 about 14 years
    so for my use it'll be: find usr/local/my_logs/*.txt -type -f -mmin +5 -exec rm {} \; <-- where 5 indicates 5 minutes?
  • user2661503
    user2661503 about 14 years
    You'll need to change to your target directory first using the cd command. I've updated the script in my original post to show this. I've tested it on my machine and it seems to work. Let me know how it goes.
  • user684503
    user684503 about 14 years
    I intend to have this running all the time, either by adding it to init.d or by sh every time the server reboots
  • user2661503
    user2661503 about 14 years
    Cool, hopefully the script above should do the job. Would you mind telling me what it's for? I'm curious :)
  • user684503
    user684503 about 14 years
    we get information from a data logger; however it's saved as file_name_timestamp.txt ... the data logger sends a copy to our web service and the backup drive (so it is getting backed up( currently the system is that every couple of days i go delete the files. (files are uploaded every 5minutes .. i want to create a script that automatically deletes all the files that are older than 5 minutes. It's a bit mor ecomplicated wiht more variables. but this is it in a nutshell