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


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

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
| improve this answer | |
  • 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 – Siva 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. – Siva 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

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

# 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-*"

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-*"
| improve this answer | |

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.