Wednesday, January 13, 2016

Bash shell script to rotate log files in certain directory using array of files

The script below will automatically rotate log files (defined in array) inside certain directory.
Note the Logfiles array in variable $Logfiles.

To use this script simply save the script to filename (you can change this): rotate_logs.sh

Change the values for variables:

Directory
Extension
Logfiles

then make it executable using:

chmod +x rotate_logs.sh

-----------------------------

#!/bin/bash

Directory='/log';
Extension='log';
Logfiles=('file_1' 'file_2' 'file_3');

echo "Directory: ${Directory}";
echo "Extension: ${Extension}";
echo "Logfiles: ${Logfiles}";

for File in "${Logfiles[@]}"
do
cd ${Directory}
echo "Rotating: ${Directory}/${File} ... "
mv ${File}.${Extension} ${File}-`date +%Y%m%d`.${Extension}
touch ${File}.${Extension}
chmod 777 ${File}.${Extension}
done

------------------------------

Once rotate daily / nightly you should also remove old log files using these lines in your cron table:

crontab -e

----------------

35 3 * * * /cron_shell/rotate_logs.sh
40 3 * * * find /log -mtime +5 | xargs rm -f

----------------

The first cron table line '/cron_shell/rotate_logs.sh' is the rotate script I described above.
The second line removes files older than 5 days.

No comments:

Post a Comment