← Catalog Matrix
DevOps

Production-Ready Bash Script to Clean and Clear Server Log Files

An automated Bash utility to safely truncate massive Linux system logs without dropping active application writing handles.

Overview & Problem Matrix

As high-traffic web applications, database clusters, and background microservices run continuously, application log outputs (like nginx/access.log, pm2.log, or application streams) can balloon into tens of gigabytes.

If you completely remove these .log files via standard deletion (rm) to recover disk capacity, active running server daemons instantly lose their open file descriptor handles. This causes applications to either crash immediately or stop logging entirely until you manually restart the underlying process.

Implementation Guide & Setup Steps

To implement this safe log truncation workflow on your Linux server environment, complete these administrative operations:

  1. Stage the Automation Script: Save the script configuration blueprint below to your secure system utility pathway as clear_logs.sh:

$ sudo nano /usr/local/bin/clear_logs.sh

  1. Lock Down Script Permissions: Elevate its runtime status and restrict view access to secure the administrative paths:

$ sudo chmod 700 /usr/local/bin/clear_logs.sh

  1. Assign the Maintenance Lifecycle: To ensure permanent host storage stability, configure a daily execution loop inside your system cron scheduler to run every morning at 3:00 AM:

$ sudo crontab -e

# Append this maintenance path rule inside the configuration console: 0 3 * /usr/local/bin/clear_logs.sh > /dev/null 2>&1

#!/bin/bash

Configuration: Define your absolute target log directory paths

LOG_DIR="/var/log/myapp" MAX_AGE_DAYS=7

Ensure the script runs with administrative root validation visibility

if [ "$EUID" -ne 0 ]; then echo "[ERROR] Please execute this storage housekeeping sequence as root (sudo)." exit 1 fi

Validate that the target destination exists before initiating processes

if [ ! -d "$LOG_DIR" ]; then echo "[ERROR] Target directory environment path does not exist: $LOG_DIR" exit 1 fi

echo "Initializing safe log cleanup routine inside: ${LOG_DIR}..."

1. Discover and truncate files directly matching your application targets safely

Using -print0 prevents code breakage if any filename pathways contain spacing anomalies

find "$LOG_DIR" -type f -name "*.log" -print0 | while IFS= read -r -d '' log_file; do

file_size_kb=$(du -k "$log_file" | cut -f1)

if [ "$file_size_kb" -gt 0 ]; then echo "[TRUNCATING] Clearing payload data from tracking node: ${log_file} (${file_size_kb} KB)"

# Truncation down to 0 bytes safely preserves the running daemon's system file descriptor handle > "$log_file" else echo "[SKIPPED] Log file is already empty: ${log_file}" fi done

2. Purge historical gzip compressed leftovers exceeding your retention limits

echo "Purging old compressed logs (.gz files) exceeding execution lifespan criteria..." find "$LOG_DIR" -type f -name "*.gz" -mtime +$MAX_AGE_DAYS -exec rm -f {} \;

echo "Server disk optimization space recovery sequence completed successfully."