Linux reports on any open files which have been unlinked

How can reports on any open files which have been unlinked (deleted) using the command-line option? Say file named app.log deleted by script but still opened by Java or Apache process on Linux machine. How do I find all such files?

You can use the lsof command to list any open files which have been removed or deleted. For instance:

sudo lsof +L1
sudo lsof -nP +L1

#############
# NOTE: You don't need sudo if you are searching for file owned by your user:group name
#############
lsof -nP +L1

Finding open files in a specific directory under Linux or Unix

Say you want to see all open files which are deleted in the /home/vivek/projects/ and all sub-dirs. For example:

lsof +D /path/to/dir/
lsof +D /home/vivek/projects/

You can combine them too. For instance:

lsof -nP +L1 +D /home/vivek/projects/

You will something as follows:

vim       465277 vivek    4u   REG              253,1    16384     0 55050555 /home/vivek/projects.demo.c.swp (deleted)

Filtering out results.

Use the grep command:

lsof ... | grep something
lsof -nP +L1 +D /home/vivek/projects/ | grep 'foo.py'

Where lsof command options are

  • +L1 : Will select open files unlinked or removed from the system but still open by any app on your Linux or Unix.
  • -n : Avoid DNS lookup (it makes lsof faster)
  • -P : Avoid converting port numbers to port names for network files (again, it makes lsof run a little faster).
  • -D /path/to/dir : Search for any open files which have been removed including sub-dirs. Want to avoid sub-dirs? Try -d /path/to/dir syntax.

Getting help

Read manual page using the man command:

man lsof
1 Like