Easy Rotate Bash Script

If you need to rotate a log file, or anything you want, without using linux logrotate standart tool, I suggest you an easy Rotate Bash Script.

First of all, i did it in Centos 7 system. I don’t know if it work in any other envirment.

I’m not a programmer so I’m sure that anyone of you could change this script as you prefer. 

Here are the script.

#!/bin/bash

now="$(date +'%Y-%m-%d-%H-%M')"

toberotated="/path/to/file/toberotated.log"
newfilename="newfile_$now"

mv $toberotated /path/to/destination/$newfilename
#systemctl restart service-to-be-restart


This script is very easy but it could have some problems.

First problem, if toberotated is managed by one service or daemon in Linux, you need to add a line a the end of the script in order to restart the daemon, if you don’t do it, the systems will never recreate a new toberotated file. 
If you are in this condition uncomment the last line of the script typing the right name of the service.

Secondo problem, if toberotated file is too big it could be necessary to rotate using tar in order to “zip” rotated file.

Here are the same script with zipped rotation

#!/bin/bash

now="$(date +'%Y-%m-%d-%H-%M')"

toberotated="/path/to/file/toberotated.log"
newfilename="newfile_$now"

tar -zcvf /path/to/destination/$newfilename".gz" $toberotated
rm -f toberotated
#systemctl restart service-to-be-restart

Last step to do is to edit cron in order to run the script how often you need.

if you have called your script something like “rotete.sh” and you want it to be run any hour just create a cron file in /etc/crond

[root@myserver ]#vim /etc/cron.d/rotatemyfile
* * * * * root /path/to/my/script/rotate.sh
[root@myserver ]#systemctl restart crond

So now your rotate bash script will run houtly, of course you can change it using crond configuration.

Any suggestion reguarding the script is appreciated on comments

Here you can find other script, maybe they could be useful

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.