5

There are some log files created after a certain amount of time with the time stamp.

/mylog/path
Log_file_2018-07-19-22-55-31Z.tgz
Log_file_2018-07-20-01-29-11Z.tgz
Log_file_2018-07-20-10-36-49Z.tgz
Log_file_2018-07-21-18-26-36Z.tgz

I need to delete older logs based on date. For example, I want only last 5 days logs and older logs should be deleted. Num of log files created daily varies. How to achieve this?

Siva
  • 9,077
Ravi
  • 759

2 Answers2

7

You can do with mtime (modified time) in find command.

 find /mylog/path -mindepth 1 -mtime +5 -delete
  • -mindepth 1 means process all files except the command line arguments.
  • -mtime +5 will check for the files modified 5 days ago.
  • -delete will delete
Siva
  • 9,077
  • Please note that +5 does not mean 5 days ago. +0 means at least 24 hours ago. +5 would therefore mean 6 days ago or older. (Source: man find) – confetti Aug 02 '18 at 06:26
  • from man..... data was last modified n24 hours ago. so +5 days means 524 hours ago...something fishy – Siva Aug 02 '18 at 07:48
  • Unfortunately find command inside the customer unit is not have fully functional. i.e, mtime option is not available. – Ravi Aug 02 '18 at 09:36
  • @Ravi which distro are you testing... can you share the error in question. – Siva Aug 02 '18 at 09:39
  • /mylog/path$ find /mylog/path -mindepth 1 -mtime +5 -delete

    find: unrecognized: -mtime BusyBox v1.19.4 (2014-10-08 20:16:45 PDT) multi-call binary.

    Linux version: 3.2.54

    – Ravi Aug 02 '18 at 09:47
  • Is there any other way I can find older files other than using -mtime? – Ravi Aug 02 '18 at 09:56
  • @SivaPrasath so to match -atime +1, a file has to have been accessed at least two days ago. - From the man page. You can try it out by using +0 too, you'll notice you won't see any files from today. – confetti Aug 02 '18 at 15:08
  • @confetti yes man page is not vaery clear for this thing, as mentioned here https://unix.stackexchange.com/a/200050/270935 – Siva Aug 02 '18 at 15:28
  • 1
    Busybox did not had -mtime earlier. Rebuild it with FEATURE_FIND_MTIME and now I can user mtime in find command. – Ravi Aug 21 '18 at 11:19
0

Since your find doesn't have the -mtime option I think this is the most simple way:

#!/bin/bash
# delete every file that's between 5 and 40 days old
for i in {5..40}; do 
    olddate=$(date --date="$i days ago" +%Y-%m-%d)
    echo "Deleting files from $olddate..."
    rm "Log_file_$olddate-*"
done

If you always want to delete log files once they aged five days but for some reason don't want to use logrotate you can use cron (crontab -e to edit crontab) to run the following script daily:

olddate=$(date --date="5 days ago" +%Y-%m-%d) && rm "/mylog/path/Log_file_$olddate-*"
confetti
  • 1,964