Linux Open Deleted Log Files Cleanup
Main Purpose:
This script is tailored to address a pivotal challenge in Linux Business As Usual (BAU) operations. Often, log files that are deleted in Linux continue to occupy space as they remain open due to certain processes.
This script provides a solution to identify and reclaim that space without having to reboot the server, restart applications, or kill any process IDs, ensuring optimal storage management while promoting system uptime.
Benefits for Linux Users:
Non-Disruptive Cleanup:
The script facilitates space recovery from open deleted files without causing system disruptions or interruptions.
Proactive Storage Management:
Regular execution can consistently reclaim storage, ensuring optimal space usage.
Optimal System Performance:
By periodically clearing lingering files, the script aids in maintaining the system's responsiveness.
Reduction in Filesystem Usage:
By actively freeing up space occupied by open deleted files, the script efficiently reduces the filesystem usage.
User Transparency:
Detailed output provides insights into which files are processed, promoting better system audit and understanding.
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.