Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
automatically delete old files in your Downloads folder
#!/usr/bin/ruby
# invoke on a regular schedule (like once a day) with:
# /path/to/trashold.rb ~/Downloads
# to automatically trash files older than 1.5 days.
require 'fileutils'
include FileUtils
THRESHOLD = 1.5 * (60 * 60 * 24)
# system("say trashing old downloaded files")
ARGV.each{|dir|
dir = File.expand_path(dir)
if File.directory?(dir)
Dir.glob(File.join(dir, "*")).select{|f|
Time.now - File.ctime(f) > THRESHOLD
}.each{|f|
trash_directory = File.expand_path(File.join("~/.Trash/", File.dirname(f)))
FileUtils::mkdir_p trash_directory
mv f, File.join(trash_directory, File.basename(f))
}
else
STDERR.puts "#{dir} is not a directory"
end
}
@aryamccarthy

This comment has been minimized.

Copy link

commented May 16, 2015

You say to invoke it on a regular schedule. Why not crontab?

@dfinninger

This comment has been minimized.

Copy link

commented May 16, 2015

Would be easier to just run a crontab -e and stick this in it:
0 12 * * * find ~/Downloads -type f -mtime +3 | xargs rm

Edit: This deletes all files in ~/Downloads that are older that 3 days.

@dfinninger

This comment has been minimized.

Copy link

commented May 16, 2015

sysadmin-things

@christiangenco

This comment has been minimized.

Copy link
Owner Author

commented May 17, 2015

@dfinninger: ooo, that's really elegant. I need to remember to use xargs more. There's a few things that one-liner is missing, though: trashing instead of deleting (which could be added to your script, I think, with mv instead of rm), and keeping the position of the files that were deleted (ie: if my script deletes a file in my Downloads folder, it will go into Trash/cgenco/Downloads/file.doc). These are important for me so I have a final check of what's getting deleted before it's actually gone forever.

@aryamccarthy: sorry; I was trying to imply that. Though you could certainly just run the script manually to get a better feel for how it's working :p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.