Linux Open Deleted Log Files Cleanup

Main Purpose:

Benefits for Linux Users:


Bash Script:

Script Name: cleanup_deleted_open_files.sh

#!/bin/bash
# Author: https://www.virtualnetworkingconcept.com/# Purpose: To view and clean up open deleted log files# Supported OS: Linux
os_type=$(uname -s)
case "$os_type" in  Linux)    # Check if running as root    if [ "$(id -u)" != "0" ]; then       echo "This script must be run as root" 1>&2       exit 1    fi
    # Check for lsof command availability    if ! command -v lsof &> /dev/null; then        echo "lsof command not found! Please install lsof."        exit 1    fi
    lsof +L1 | grep '(deleted)' | grep '\.log' | awk '$7 != 0' > /tmp/open_deletedfiles.txt
    # Check if the file is not empty    if [[ ! -s /tmp/open_deletedfiles.txt ]]; then        echo "No open deleted log files found."        rm /tmp/open_deletedfiles.txt        exit 0    fi
    mapfile -t lines < /tmp/open_deletedfiles.txt
    for line in "${lines[@]}"; do        pid=$(echo "$line" | awk '{print $2}')        puser=$(echo "$line" | awk '{print $3}')        pcomm=$(echo "$line" | awk '{print $1}')        fd=$(echo "$line" | awk '{print $4}' | grep -o '^[0-9]*')        deleted_file=$(ls -l /proc/$pid/fd/$fd 2>/dev/null | cut -d '>' -f 2- | tr -d ' ')
        if [ -n "$deleted_file" ]; then            # Truncate the file to free up space            > "/proc/$pid/fd/$fd"            echo -e "USER=$puser | COMMAND=$pcomm | PID=$pid | FD=/proc/$pid/fd/$fd | FILE=$deleted_file | SPACE=cleared"        fi    done
    # Cleanup    rm /tmp/open_deletedfiles.txt    ;;  *)    echo "This script is not supported for $os_type."    ;;esac


Conclusion:

For Linux users, particularly those overseeing critical operations, this script is a vital asset. It streamlines storage management, ensures system efficiency, and does so with minimal operational disruption.