Last Updated: February 25, 2016
·
2.237K
· yitsushi

Remove files older than 7 days

Sometimes I need to remove files that older than N days (or empty file?). 2 weeks, 1 week, 1 month etc.

find DIRECTORY -size 0 \
  -or -not -newermt `date --date=@$(($(date +"%s")-(60*60*24*7))) +"%Y-%m-%d"` \
  -exec rm {} \;

It's pretty, small and useful as a cron job. If we have a script then we can write it with variables:

#/usr/bin/env bash

DAYS=7
# relative or absolute
DIRECTORY="/my/target/directory"
targetTimestamp=$(($(date +"%s")-(60*60*24*${DAYS})))
targetDate=`date --date=@${targetTimestamp} +"%Y-%m-%d"`

find "${DIRECTORY}" -size 0 \
  -or -not -newermt "${targetDate}" \
  -exec rm {} \;

1 Response
Add your response

Surely it would be more concise to use find's modification or creation time functions:

find DIRECTORY -type f -and \( -size 0 -or -mtime +7 \) -exec rm {} \;

This will remove only files (not directories) that are older than 7 days

over 1 year ago ·