Why does mcedit recommend removing hardlinks when saving a file

filesystemshard link

Whenever I use mcedit to edit a file that is hard linked somewhere and I want to save the file, the editor asks me if I want to remove the hard links. Is that common behavior on Linux or is mcedit "special" in doing so? Why would regular applications (not fsck or other admin tools) care about hard links?

Best Answer

When you want to modify a file, you have two options, each with its benefits and drawbacks.

  • You can overwrite the file in place. This does not use any extra space, and conserves the hard links, permissions and any other attribute beyond the content of the existing file. The major drawback of doing this is that if anything happens while the file is being written (the application crashes, or the power goes out), you end up with a partially written file.
  • You can write the new version of the file to a new file with a different name, then move it into place. This uses more space and breaks hard links, and if you have write permissions on a file but not on the directory it contains, you can't do it at all. On the flip side, the old version of the file is atomically replaced by the new version, so at every point in time the file name points to a valid, complete version of the file.

Mcedit is asking you which strategy to choose. Strangely though, mcedit's default strategy, for files with a single directory entry, is to truncate the existing file, putting your data at risk. Only when the safe strategy would break a hard link does it give you the opportunity to use it. You can change this in the “Edit save mode” dialog from the Options menu: “quick save” means overwrite, “safe save” means save to a temporary file then rename. When safe mode is chosen, you don't get a choice not to break symbolic links.

(Observations made on mc 4.8.3. If this is still the case in the latest version, consider reporting it as a design bug — “safe mode” should be the default, and you should get an option not to break hard links in that case.)

Good editors such as Vim or Emacs let you choose the default strategy.