0

I've a system that writes files to /var/tmp/log/my.log, I want to write a shell script to rotate the log files when it reaches 1KB limit, so my my.log becomes my.log.1, my.log.1 becomes my.log.2 and so on until my.log.10 and then the other files are deleted.

I got some part of the script but don't know how to change the file names.

#!/bin/bash file_size=`du -b /var/tmp/log/my.log` if($file_size -gt 1024) do mv my.log my.log.1 done fi

I need to move my.log to my.log.1 when my.log reaches 1KB limit and then move my.log.1 to my.log.2 so that the my.log can move to my.log.1 after it reaches 1KB second time and so on. Is there any way to do this without using logrotate ?

3
  • What is the language you write your script? IMO it's not bash Commented Dec 23, 2018 at 8:53
  • I want to write a shell script, it doesn't matter which shell, but I prefer bash
    – shanu
    Commented Dec 23, 2018 at 8:55
  • So write it in bash And define how many old logs you want to keep Commented Dec 23, 2018 at 8:57

1 Answer 1

2

You can make rotation with something like this:

for i in {9..1}; do
    if [[ -f my.log.${i} ]]; then
        mv -f my.log.${i} my.log.$((i+1))
    fi
done
mv -f my.log my.log.1
touch my.log

this will keep 10 rotated logs, up to my.log.10, which will be overwritten with newer logs on every rotation once script does more then 10 rotations.

Depending on how many logs you want to keep you need to lower or increase the range in for loop.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .