Skip to content

Instantly share code, notes, and snippets.

@momchilov
Last active August 29, 2015 14:15
Show Gist options
  • Save momchilov/b29c6222809a063743fd to your computer and use it in GitHub Desktop.
Save momchilov/b29c6222809a063743fd to your computer and use it in GitHub Desktop.
A script to get rid of large log files automatically.
#!/bin/bash
#
# Description:
# Check disk space, find and delete FILE_NAMES larger then
# FILES_LARGER_THEN, if disk space for the partition where
# FILES_DIRECTORY is located is less then DISK_SPACE_PERCENTAGE.
# Useful for keeping disk space under control in directories, such as
# /var/log. You can add it to your crontab, so it executes every
# 3 hours, like so:
#
# 0 */3 * * * /path/to/script/check_disk_space_and_delete_logs.sh 2>&1 | /usr/bin/logger -t log_files_maintenance
#
# Where to check for files that CAN be deleted so that disk space
# can be freed.
FILES_DIRECTORY=/var/log
# File uses n units of space. The following suffixes can be used:
#
# 'b' for 512-byte blocks (this is the default if no suffix is
# used)
# 'c' for bytes
# 'w' for two-byte words
# 'k' for Kilobytes (units of 1024 bytes)
# 'M' for Megabytes (units of 1048576 bytes)
# 'G' for Gigabytes (units of 1073741824 bytes)
FILES_LARGER_THEN=200M
# Specify how much used % disk space should cause deletion of files
DISK_SPACE_PERCENTAGE=80
# File name must contain
FILE_NAMES=("*.log" "*.out")
### DO NOT EDIT ###
SEARCH_STRING=""
for string in $FILE_NAMES; do SEARCH_STRING+=" -name $string"; done
DISK_SPACE_PERCENT_AVAIL="$(df -H $FILES_DIRECTORY | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{print $5}' | tr -d %)"
PARTITION=`df -H /var/log | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{print $6}'`
if [[ $DISK_SPACE_PERCENT_AVAIL > $DISK_SPACE_PERCENTAGE ]]; then
echo -e "[*] Deleting files larger then $FILES_LARGER_THEN on $PARTITION partition in $FILES_DIRECTORY directory:"
output=`/usr/bin/find $FILES_DIRECTORY $FILE_STRING -type f -size +$FILES_LARGER_THEN -exec rm -v {} \; 2>&1`
if [[ -z "$output" ]]; then echo -e " - No files older then $FILES_LARGER_THEN hours found. No files will be deleted."; fi
else
echo -e "[*] Disk space on $PARTITION partition is at $DISK_SPACE_PERCENT_AVAIL%, less then $DISK_SPACE_PERCENTAGE%. No attempt to delete files will be made."
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment