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 ?

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

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))
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.

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.