Delete and compress logfiles

Hello, together
Since last month I work with Ruby.
I realised that I leave in the work often log files which are older than
1 month.
Now I want to delete them, however, a ruby script would be more sensible

I know, I can do that in shell, but I want it in ruby.

Can someone send me a example script who does that?

1 Like

In Ruby you can delete files with FileUtils.rm

For finding older files you’ll want to use File.mtime (modified time)

To compare dates it will best to use DateTime.

To get you started you can do something like this:

require 'fileutils'
require 'date'

current_day =

# This will get log files for all subdirectories
Dir["./**/*.log"].each do |file|
  file_day = File.mtime(file).to_datetime.jd

  if current_day - file_day >= 20
    FileUtils.rm file

I haven’t tested this but it should work.

1 Like