Skip to content

lsof Command Cheat Sheet

lsof lists information about files opened by processes. In Linux, everything is a file (pipes, sockets, directories, devices), making lsof an incredibly powerful debugging tool.

Note: lsof usually requires sudo to see processes owned by other users.


Synopsis

lsof [OPTIONS]

Network Troubleshooting (-i)

List All Network Connections

sudo lsof -i

Filter by Protocol (TCP/UDP)

sudo lsof -i tcp
sudo lsof -i udp

Find Process Using a Port

Critical for "Address already in use" errors.

sudo lsof -i :80
sudo lsof -i :22

Filter by Host

sudo lsof -i @192.168.1.5

File Troubleshooting

Who is using this file?

Find why you cannot unmount a drive.

sudo lsof /mnt/backup

List Files Opened by User (-u)

sudo lsof -u alice

List Files Opened by Process (-p)

sudo lsof -p 1234

List Files Opened by Command (-c)

Matches command name (regex supported).

sudo lsof -c nginx
sudo lsof -c ssh

Advanced Usage

Find Deleted Files Held Open

If you deleted a huge log file but disk space didn't free up, a process is still holding it open.

sudo lsof +L1
Or look for "deleted" in output:
sudo lsof | grep deleted
Fix: Restart the process holding the file.

Directories (+d / +D)

  • +d: List open files in directory (non-recursive).
  • +D: List open files in directory (recursive).
sudo lsof +D /var/log

Combine logic (-a)

By default, options are ORed. Use -a to AND them. "List files opened by User AND related to SSH".

sudo lsof -a -u faruk -c ssh

Repeat Mode (-r)

Run repeatedly (like watch).

sudo lsof -r 2 -i :80
(Checks port 80 every 2 seconds).


Output Columns

  • COMMAND: Name of the program.
  • PID: Process ID.
  • USER: Process owner.
  • FD: File Descriptor.
    • cwd: Current working directory.
    • txt: Program text (code).
    • mem: Memory-mapped file.
    • 0u, 1u, 2u: Stdin, Stdout, Stderr.
  • TYPE: File type (DIR, REG, CHR, FIFO, IPv4).
  • DEVICE: Disk ID.
  • SIZE/OFF: File size or offset.
  • NODE: Inode number.
  • NAME: Path or socket details.

Notes

  • If lsof is slow, use -n (no DNS resolution) and -P (no Port name resolution).
    sudo lsof -n -P -i :80