Skip to content

Instantly share code, notes, and snippets.

@ngoue
Created December 11, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngoue/abfaac6b1138df71f9af to your computer and use it in GitHub Desktop.
Save ngoue/abfaac6b1138df71f9af to your computer and use it in GitHub Desktop.
Bash Log Rotation - Mac OSX
#! /bin/bash
##
# Log rotation script
#
# Author: Jordan Gardner (jordanthomasg@gmail.com)
# Version: 1.0
# Last Revision: 12/11/2015
#
# Copyright (c) 2015 Jordan Gardner
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
##
# Script Variables
LOG_DIR="/path/to/logs" # Log directory
LOG_FILE="backup.log" # Log filename to rotate (MUST CONTAIN ONE AND ONLY ONE `.`)
MAX_SIZE="50000" # Threshold filesize (in bytes)
MAX_LOGS="0" # Max number of logs to keep - zero is unlimited
##
# Rotate Logs
cd $LOG_DIR
# Check for an existing $LOG_FILE
if [ -a $LOG_FILE ]; then
# Check if the logs need rotating
if [ $( stat -f%z $LOG_FILE ) -ge $MAX_SIZE ]; then
# Get the count of files
FILE_COUNT=$(( $( ls -1 | wc -l ) )) # doing some fun embedding to strip the $FILE_COUNT of all whitespace
# Rotate the log files
for LOG in $( ls -1 | sort -rn -t. -k3 ); do
# Check for $MAX_LOGS
if [ $MAX_LOGS -ne 0 ] && [ $FILE_COUNT -gt $MAX_LOGS ]; then
# Remove the log file
rm $LOG
else
# Set new filename
RENAME="$LOG_FILE.$FILE_COUNT"
# Check file extension
EXT="${LOG##*.}"
if [ $EXT == "gz" ]; then
# Just rename already gzipped files
mv $LOG "$RENAME.gz"
else
# Rename the log file
mv $LOG $RENAME
# Gzip all log files except $LOG.1
if [ $FILE_COUNT -ne 1 ]; then
gzip "$RENAME"
fi
fi
fi
# Reduce the $FILE_COUNT
let "FILE_COUNT -= 1"
done
# Create new log when finished rotating
touch $LOG_FILE
fi
else
# Create new log if no logs exist
touch $LOG_FILE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment