BASH - Delete files older than 3 months?
Asked Answered
W

2

16

Delete files older than 3 months how?

For 90 days i know:

find /tmp/*.log -mtime +90 -type f -delete

But how do i know 3 months equal to always 90 days? how many exact days? Is there more better way to tell the -mtime to follow months?

Whereas answered 23/8, 2017 at 11:19 Comment(2)
Why is it so critical for you to use the inexact time-unit month?Bialy
Make it 93 days and just accept that you may have a delayed deletion of files for short periods. Life is too short for being picky :-)Max
H
20

If you want exact number of days for 3 months then you can use:

days=$(( ( $(date '+%s') - $(date -d '3 months ago' '+%s') ) / 86400 ))

and use it as:

find /tmp/*.log -mtime +$days -type f -delete

Or directly in find:

find /tmp/*.log -type f \
-mtime "+$(( ( $(date '+%s') - $(date -d '3 months ago' '+%s') ) / 86400 ))" -delete
Huggins answered 23/8, 2017 at 11:56 Comment(0)
M
0

Just in case, find supports other time difference options, including: -amin, -atime, -cmin, -ctime, -mmin, and -mtime.

#! /usr/bin/env bash

# For example, today is 2023-12-12.
# Let's find all files since the start of the month (i.e. 2023-12-01).

declare currentSecs="$( date -u -- '+%s'; )";
declare previousSecs="$( date -ud '2023-12-01' -- '+%s'; )";

find . -mmin "-$(( (currentSecs - previousSecs) / 60 ))";

# -mmin n
# File's data was last modified less than, more than or exactly n minutes ago.

Source: man find (find (GNU findutils) 4.8.0).

Myron answered 12/12, 2023 at 14:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.