How to identify List of Open Deleted files in Linux

Main Purpose:

The script named list_deleted_open_files.sh has been designed to address a distinct aspect of Linux system operations.

On Linux systems, it's common for log files to be deleted but remain open due to certain processes holding onto them. Instead of cleaning them, this script lists these files, providing insights into which files are currently in this state.

This can be particularly useful for monitoring, auditing, and subsequent manual or automated actions.

Benefits for Linux Users:


Bash Script:

Script Name: list_deleted_open_files.sh

#!/bin/bash

# Author: https://www.virtualnetworkingconcept.com

# Purpose: To view open deleted log files only

# 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

            echo -e "USER=$puser | COMMAND=$pcomm | PID=$pid | FD=/proc/$pid/fd/$fd | FILE=$deleted_file "

        fi

    done


    # Cleanup

    rm /tmp/open_deletedfiles.txt

    ;;

  *)

    echo "This script is not supported for $os_type."

    ;;

esac


Conclusion:

The list_deleted_open_files.sh script is an invaluable diagnostic tool for Linux users. While it doesn't perform cleanup actions directly, its ability to shed light on hidden file activities makes it essential for routine system monitoring and subsequent optimization efforts.