Skip to content

Instantly share code, notes, and snippets.

@pelgrim
Created July 6, 2012 15:29
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save pelgrim/3060901 to your computer and use it in GitHub Desktop.
Save pelgrim/3060901 to your computer and use it in GitHub Desktop.
A Ruby script to delete files older than X days in a given directory.
#!/usr/bin/env ruby
# A Ruby script to delete files older than X days in a given directory. Pretty simple.
# Like this: file_control.rb /User/pelgrim/Documents '*.pdf' 7
# The command above you remove ALL your pdfs inside Documents older than SEVEN DAYS.
# Quickly written by pelgrim < guskald at gmail dot com >
unless ARGV.size == 3
puts "Usage: file_control <directory> <filename pattern> <max age>"
exit 1
end
directory, file_pattern, max_age = ARGV[0], ARGV[1], ARGV[2].to_i
unless File.exists?(directory)
puts "Bad directory #{directory}!"
exit 2
end
unless max_age > 0
puts "Max age must be greater than zero! I don't want to remove ALL your files!"
exit 3
end
def file_age(name)
(Time.now - File.ctime(name))/(24*3600)
end
Dir.chdir(directory)
Dir.glob(file_pattern).each { |filename| File.delete(filename) if file_age(filename) > max_age }
@pelgrim
Copy link
Author

pelgrim commented Sep 3, 2013

Or you could simply do

find -name "" -type f -ctime -exec rm {} ; or something like that.

@zmh-git
Copy link

zmh-git commented Sep 3, 2014

Not if you want it explicitly in ruby for some reason.
For bash that would do fine though

@ntnmrndn
Copy link

ntnmrndn commented Jun 2, 2016

Be careful about the timezone. If ran in a rails app for example file_age will be local computer time and Time.now will be UTC+0

@krisleech
Copy link

You can also use File.mtime which I found to work when extracting a tar file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment