2

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?

  • Did you consider using something like logrotate? – Kusalananda Aug 2 '18 at 6:17
  • I do not need to 'rotate' logs. Just need to delete older logs – Ravi Aug 2 '18 at 9:39
  • 1
    That is pretty much the definition of log file rotation. – Kusalananda Aug 2 '18 at 9:40
5

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
  • 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 2 '18 at 6:26
  • from man..... data was last modified n*24 hours ago. so +5 days means 5*24 hours ago...something fishy – msp9011 Aug 2 '18 at 7:48
  • Unfortunately find command inside the customer unit is not have fully functional. i.e, mtime option is not available. – Ravi Aug 2 '18 at 9:36
  • @Ravi which distro are you testing... can you share the error in question. – msp9011 Aug 2 '18 at 9:39
  • 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-*"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.