I have logs in the following format: YYYYMMDD

I want to compress old logs (older then current day) and maybe move them to a different directory afterwards.

Can I do this in logrotate, or do I have to use a custom script in cron?


Here's a quickie script which will do what you need:

TODAY=$(date +'%Y%m%d')

[ -d $OLDLOGS ] || mkdir -p $OLDLOGS


for LOG in $(ls | egrep '^[[:digit:]]{8}$'); do
    [ $LOG -lt $TODAY ] && gzip $LOG && mv $LOG.gz 

Make the script executable:

$ chmod +x /where/you/put/this/script

The crontab entry will look like:

30 0 * * * /where/you/put/this/script

Just adjust LOGDIR and OLDLOGDIR. At 12:30am it will move all logs in the format of YYYYMMDD for the previous (and earlier, if any) days.

  • 5
    Yes, but it doesn't really answer my question. My question was whether I can use logrotate for this. Jun 24 '11 at 11:04
  • @Let_Me_Be - I thought it was implicit in my answer. No, logrotate won't do exactly what you want. That is, you can't only match YYYYMMDD files. Otherwise you can come close by using nodateext, olddir, compress, and daily options.
    – unpythonic
    Jun 24 '11 at 11:26

logrotate can do it with olddir if your log file name is the same every time it runs and you can add dates. If your log file name changes i.e. YYYYMMDD then logrotate won't do it for you.

# sample logrotate conf file
dateformat %Y%m%d.
extension log
olddir ./logarchive

/logs/sys.log {
    rotate 7

Copies and gzips /logs/sys.log to /logs/logarchive/sys.20120101.log.gz, keeps one week worth of logs.

  • 2
    This is not the answer. The logs already have datestamps, and are effectively rotated Let_Me_Be just wants to compress them. I believe @jmtd is right. Apr 7 '17 at 1:22

logrotate itself does not do this. I'd recommend writing a supplementary script and invoking it from logrotate using the postrotate option in the configuration.

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.