Gzip Old Log Files Shell Script Linux (find, mtime, Cron)

gzip old log files shell script

Logrotate handles many apps, but custom app folders still need a gzip old log files shell script — find by age, compress, and optionally prune archives before disks fill.

What this script does

  • Targets directory argument (default /var/log/myapp)
  • Compresses *.log older than N days
  • Skips *.gz files
  • Optional DELETE_DAYS removes ancient .gz
  • Dry-run mode lists actions

Prerequisites

  • find and gzip
  • Write permission on log dir
  • Test dry-run before production cron

Step 1: Save the script

sudo nano /usr/local/bin/gzip-old-logs.sh
sudo chmod +x /usr/local/bin/gzip-old-logs.sh

Step 2: Full script (scroll to read)

gzip-old-logs.sh
#!/usr/bin/env bash
set -euo pipefail

DIR="${1:-/var/log/myapp}"
AGE_DAYS="${2:-7}"
DELETE_DAYS="${DELETE_DAYS:-90}"
DRY="${DRY_RUN:-0}"
LOG="/var/log/gzip-old-logs.log"

log(){ echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }

[[ -d "$DIR" ]] || { log "missing dir $DIR"; exit 1; }

do_gzip(){
  local f="$1"
  if (( DRY )); then
    log "DRY gzip $f"
  else
  gzip -f "$f" && log "gzipped $f"
  fi
}

while IFS= read -r -d '' f; do
  do_gzip "$f"
done < <(find "$DIR" -type f -name '*.log' -mtime +"$AGE_DAYS" -print0 2>/dev/null)

while IFS= read -r -d '' f; do
  if (( DRY )); then
    log "DRY delete $f"
  else
    rm -f "$f" && log "deleted $f"
  fi
done < <(find "$DIR" -type f -name '*.gz' -mtime +"$DELETE_DAYS" -print0 2>/dev/null)

Scroll inside the box to read the full script.

Step 3: Configure settings

Shell script gzipping old log files
Shell script gzipping old log files

Step 4: Test manually

DRY_RUN=1 ./gzip-old-logs.sh /var/log/nginx
sudo ./gzip-old-logs.sh /var/log/app 14

Schedule with cron

sudo crontab -e

Add:

15 3 * * * /usr/local/bin/gzip-old-logs.sh /var/log/myapp 7 >> /var/log/gzip-old-logs.log 2>&1

Related tutorials

Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).