The Linux Page

How do I find the vim editor that locks my file?

Files piling up...

Once in a while, when I try to open a file, I get an error message saying that the file is already being edited in another instance of vim. I often have over 10 instances of vim opened so it makes it rather complicated to find out which one is the culprit.

In most likelihood, the error message includes all the information that you need. Here is an example:

Found a swap file by the name "/etc/apache2/sites-available/"
          owned by: root   dated: Fri Jan 22 16:19:51 2021
         file name: /etc/apache2/sites-available/
          modified: no
         user name: root   host name: monster
        process ID: 397 (still running)
While opening file "/etc/apache2/sites-available/"
             dated: Mon Nov 28 21:53:54 2022
      NEWER than swap file!

(1) Another program may be editing the same file.  If this is the case,
    be careful not to end up with two different instances of the same
    file when making changes.  Quit, or continue with caution.
(2) An edit session for this file crashed.
    If this is the case, use ":recover" or "vim -r /etc/apache2/sites-available/"
    to recover the changes (see ":help recovery").
    If you did this already, delete the swap file "/etc/apache2/sites-available/"
    to avoid this message.

Swap file "/etc/apache2/sites-available/" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:

As we can see, there is an entry which says: process ID. I highlighted the identifier in red to make it easier to find.

That's pretty much it. That is the process which has that file already opened. You can find the process using

$ ps -ef | grep 397

If you are like me and most often open vim with filenames on the command line, you'll know which window to look for. At least, in my case, that's how I rock.

Funny thing is, process 397, when I checked on it, was "[kauditd]". Yes. A kernel daemon. I suppose that a process ran in a previous reboot and had PID 397 long enough that the kernel could not reuse it. Later, one of my vim instances reused that number and I probably rebooted or had to reset the computer with vim still running with that PID.

In other words, for me, the message above was spurious. No other instances had that file opened and I could just delete the file. Since I very quickly save my changes, it is rather rare that I need the swap file to restore anything. In fact, I don't remember the last time that happened to me.