← Runnable Projects

阅读中文版本

Bash Log Rotation Script

A small Bash script that finds .log files older than a threshold, supports a dry run, and compresses matched files with gzip.

beginnerbashverified-runnable

Project

bash-log-rotate

Entry point: rotate.sh

Install

bash --version

Run

bash rotate.sh ./logs 30

Test

DRY_RUN=1 bash rotate.sh ./logs 30

Expected output

Dry run lists only old.log; the real run creates old.log.gz and leaves new.log untouched.

Dependencies

  • bash >=4
  • gzip >=1.10

Verification evidence

Bash 5.2.37: dry run listed only the 40-day-old log; real run produced old.log.gz and kept new.log.

Security note

gzip replaces the original file; always run the dry run first and test on a disposable directory before using it on production logs.

What it does

Finds *.log files in a directory older than N days and compresses them. DRY_RUN=1 prints what would be rotated without touching files.

#!/usr/bin/env bash
set -euo pipefail
dir=${1:?usage: rotate.sh <dir> [days]}
days=${2:-30}
dry=${DRY_RUN:-0}
find "$dir" -maxdepth 1 -type f -name '*.log' -mtime +"$days" -print0 |
while IFS= read -r -d '' file; do
  if [ "$dry" = "1" ]; then
    echo "would rotate: $file"
  else
    gzip -f "$file"
    echo "rotated: $file -> $file.gz"
  fi
done

Run and verify

mkdir -p logs
: > logs/old.log
: > logs/new.log
touch -d '40 days ago' logs/old.log
DRY_RUN=1 bash rotate.sh logs 30
bash rotate.sh logs 30
ls logs

Expected output: the dry run lists only old.log; the real run produces old.log.gz and leaves new.log unchanged. Verified with Bash 5.2.37: both runs matched this behavior.

Limitations

Processes only the top level of one directory, uses modification time rather than log content, and does not coordinate with a running writer. For production, use logrotate or the platform’s logging pipeline, and ensure the writer reopens files after rotation.