0
0
Bash Scriptingscripting~5 mins

Log rotation script in Bash Scripting

Choose your learning style9 modes available
Introduction
Log rotation helps keep log files from getting too big and uses less disk space. It also makes it easier to find recent logs.
When your application creates large log files that grow over time.
To keep logs organized by date or size for easier reading and backup.
To automatically delete old logs and save disk space.
When you want to avoid manual cleanup of log files.
To prepare logs for archiving or sending to another system.
Syntax
Bash Scripting
#!/bin/bash

LOG_DIR="/path/to/logs"
MAX_SIZE=10485760  # 10 MB in bytes

for LOG_FILE in "$LOG_DIR"/*.log; do
  if [ -f "$LOG_FILE" ]; then
    FILE_SIZE=$(stat -c%s "$LOG_FILE")
    if [ "$FILE_SIZE" -ge "$MAX_SIZE" ]; then
      mv "$LOG_FILE" "$LOG_FILE.$(date +%Y%m%d%H%M%S)"
      touch "$LOG_FILE"
    fi
  fi
done
Use #!/bin/bash at the top to specify the script runs in bash.
The script checks each .log file size and renames it if too big, then creates a new empty log.
Examples
Set log directory and max size to 5 MB for rotation.
Bash Scripting
# Rotate logs larger than 5 MB
LOG_DIR="/var/log/myapp"
MAX_SIZE=5242880
Rename log file by adding the current date in YYYY-MM-DD format.
Bash Scripting
mv "$LOG_FILE" "$LOG_FILE.$(date +%Y-%m-%d)"
Create a new empty log file after rotating the old one.
Bash Scripting
touch "$LOG_FILE"
Sample Program
This script creates a sample log file, then checks if it is bigger than 1 KB. If yes, it renames the log with a timestamp and creates a new empty log file.
Bash Scripting
#!/bin/bash

LOG_DIR="./logs"
MAX_SIZE=1024  # 1 KB for demo

mkdir -p "$LOG_DIR"

# Create a sample log file with some content
LOG_FILE="$LOG_DIR/sample.log"
echo "This is a test log line." > "$LOG_FILE"
for i in {1..50}; do echo "Line $i" >> "$LOG_FILE"; done

# Log rotation script
for LOG_FILE in "$LOG_DIR"/*.log; do
  if [ -f "$LOG_FILE" ]; then
    FILE_SIZE=$(stat -c%s "$LOG_FILE")
    if [ "$FILE_SIZE" -ge "$MAX_SIZE" ]; then
      mv "$LOG_FILE" "$LOG_FILE.$(date +%Y%m%d%H%M%S)"
      touch "$LOG_FILE"
      echo "Rotated $LOG_FILE"
    else
      echo "$LOG_FILE size is under limit"
    fi
  fi
done
OutputSuccess
Important Notes
Make sure the script has execute permission: chmod +x script.sh
Adjust MAX_SIZE to your desired log file size limit in bytes.
Use full paths to avoid confusion when running the script from different folders.
Summary
Log rotation scripts help manage log file sizes automatically.
They rename large logs with timestamps and create new empty logs.
This keeps logs organized and prevents disk space issues.