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
*.logolder than N days - Skips
*.gzfiles - Optional
DELETE_DAYSremoves 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
- Works alongside custom log rotation
- Alert before cleanup: disk space alert
- Do not gzip logs still open by a running process without copytruncate policy

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
- Linux Backup Shell Script: Files & Database to Remote Server
- Cron Jobs in Linux: Schedule Tasks with crontab
- SSH Key Authentication on Linux Servers
Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).