Lsof Command
To view open files and the users or processes responsible for them, we use the lsof utility. By default, lsof is pre-installed in most distributions. However, if you do not have it installed, you can use the package manager to install it on your system.
Debian/Ubuntu
On Debian, run the command:
Arch/Manjaro
On Manjaro and other Arch-based distributions, use pacman by running the command:
CentOS/REHL/Fedora
For CentOS and the REHL family, you can use dnf:
Use lsof Command to List Open Files for a Linux Process
Like most Linux commands, the lsof utility is incredibly simple to use. Start by typing the command lsof: Once you run the command above, lsof should return information about the open files in the system. Note: if you have sudo privileges, run the command with sudo to avoid “permission denied” errors on specific files. As shown in the output above, the lsof output has the following columns: Now that you understand what the contents of the lsof command printout represent, let us use the command to filter for specific information.
How to Filter for Specific Process
To filter for only specific files opened by the specific process, we can use either the process name or the PID value. For example, to show files used by the firefox process, we can use the command: The command will show all the files opened by the firefox process. To filter by process ID, we can use the -p option and pass the process ID. You can use the top command to get the process ID of the target process. For example, to get the PID of the firefox process, we can use the command: Once you have the PID of the target process, use lsof to show the open files: The above command will print the files opened by the process with the PID specified.
How to Filter for a Specific User
To view only the files opened by a specific user, we can use the -u flag. For example, to filter for the Debian user, use the command:
How to Filter for a Specific File
Suppose you only want to know the process and the user who opened a specific file. To do this, pass the name of the file to lsof: The above will only filter for the specific file and return the related information, including the user, process ID, and more.
Wrapping Up
In this simple tutorial, we discussed how to query the system for information about open files using the lsof command in Linux. Here are some additional commands for you to list the content of a directory in the terminal.