The Linux lsof command lists open files and provides plenty of extra information.

Learn how to use lsof with these practical examples.

What Islsof?

Tux mascot jumping from Windows to Linux.

Available natively within any Linux operating system, thelsofcommand provides a list of open files.

Let’s have a look at basiclsofoutput.

We will be runninglsofas root.

Terminal window showing the manual page for the Mutt email client on Linux

Alternatively, it’s possible for you to execute

.

Thelsofcommand lists various columns.

First up we see theCOMMANDcolumn which lists the binary which is holding the open file/open file lock.

Article image

TheTASKCMDcolumn holds the task command name.

Again it is only visible if the given line is a task and not a process.

TheUSERcolumn lists the user who started the process/task.

Start of lsof output and lsof column names in a Bash terminal

When looking at regular files, theFDcolumn will for example show102uor13w.

TheTYPEcolumn is quite self-explanatory; it indicates whether a regular file or a directory open lock is being held.

TheDEVICEcolumn generally lists the gadget numbers, separated by commas, for most types of files.

Running a test.sh script which will hold open directories as later listed by lsof

It can also list for exampleTCPorUDPwhen the given lock is an open Internet connection.

Note that this should only be done in situations where it makes sense to do so.

You know the open filename of the hanging process but do not know what thePIDfor that process/task is.

lsof with a grep for matching text is a great way to search the verbose lsof output

Let’s see how this works out practically.

We can also see both thePIDfor thetest.shscript as well as for thesleepcommand.

We could also anticipate thatlsofhas a header line that containsPIDand this text will be passed onto kill as well.

Kill a process using kill -9 based on a lsof search using grep

For Bash multi-threaded programming, seeHow to Use Multi-Threaded Processing in Bash Scripts.

test.sh script killed output as a result of the kill executed in the other terminal