Does vim/vi/nano/etc lock files from being written to?

11,286

vim doesn't do this, but I'm not sure about the others. However, there's a very simple way to check this:

Open up two terminal windows (konsole, gnome-terminal, etc), and run the following commands in the first console:

touch ~/test.txt
vim ~/test.txt

Now, in your second console, type the following:

echo "This is a test" >> ~/test.txt

If the file is locked by vim, your command in the second console will fail, as the file cannot be written to. It won't fail. Repeat with whatever editor you want as step #2 in the first console.

Obviously, if you try and save any changes in your first console, you're wandering into uncharted territory, but as far as appending to log files go, this is safe.

Some editors, such as vim, gedit and others, create a "shadow" file when opening a file to indicate that the file is open in the editor. This is not locking, and does nothing to other applications on your system - it merely serves as a way for the editor to know that the file is open.

Share:
11,286

Related videos on Youtube

kemra102
Author by

kemra102

Updated on September 18, 2022

Comments

  • kemra102
    kemra102 over 1 year

    Pretty much as the title suggests, my colleague asserts that using a text editor instead of a parser (such as less) locks the file and in the case of logfiles makes it such that the logfile cannot be written to.

    I have never heard of this before and just some initial testing finds this to not be the case. Additionally, I cannot find anything about this on a Google search to suggest where he might have got this idea from.

    • Rmano
      Rmano over 9 years
      The described behavior is very common in Windows (you normally can't write to files opened for read --- try to recompile a LaTeX document while watching the output in Acrobat...). Linux/Unix normally do not do mandatory locking. Now, if something manages to write to a file from two programs simultaneously... anything can happen.
  • kemra102
    kemra102 over 9 years
    That's basically what I already did, I just wanted to run it past others to see if this perhaps holds any weight in history or such but not that I can find. Thanks!
  • Braiam
    Braiam over 9 years
    emacs does, nano is just way too simple.
  • muru
    muru over 9 years
    @Braiam didn't happen to me. Does it need to be configured?
  • Braiam
    Braiam over 9 years
    I just open a file, twice, and it ask if I want to recover the previous session and/or someone else is editing the file
  • muru
    muru over 9 years
    @Braiam I just did the same thing at it opened quietly without any questions. Since I never use it I have never customized it.
  • phils
    phils almost 6 years
    @muru, Emacs (dating back to version 17) will attempt to lock files (for other Emacs users, at least), unless the create-lockfiles user option has been disabled. See also File Locks.