16

Let's say I have two files file1 and file2:

$ echo aaa >file1
$ ln file1 file2

Then I check that the inodes are the same:

$ ls -i
18749779 file1  18749779 file2

which shows that the two files are actually the same. Now I edit file1 in Emacs, and add a line with for example the text bbb, and save it and exit Emacs.

Now I get:

$ ls -i
18749781 file1  18749779 file2
$ cat file1
aaa
bbb
$ cat file2
aaa

So the hard link is broken. Note that this does not happen when I edit the file in vim, or if I simply do echo bbb >>file1..

How can I prevent Emacs from breaking hard links?

Update:

Note that I have

(require 'backup-dir)
(setq bkup-backup-directory-info
      '((t  "~/.emacs-backups/" ok-create full-path )))

in my ~/.emacs init file. If I edit file1 using emacs -Q file1 instead, I get a file called file1~ in the current directory that links to file2 (has the same inode) but the file1~ has not been modified (so it is identical to the old file1).. This is not what I desire. I would like both file1 and file2 to be the same file, and to include the updated file contents..

Håkon Hægland
  • 3,608
  • 1
  • 20
  • 51

1 Answers1

14

@Hakon solved his own problem with:

(setq backup-by-copying t)

If you prefer to retain the default behaviour, and use back-up-by-copying only for hard-linked files, you can use this instead (and leave backup-by-copying set to nil):

(setq backup-by-copying-when-linked t)

In addition, as pointed out by @Harald you can set back-up-by-copying as a file-local variable instead, to turn on this feature only for individual files.

The explanation of this behaviour from the Emacs manual:

Backup files can be made by copying the old file or by renaming it. This makes a difference when the old file has multiple names (hard links). If the old file is renamed into the backup file, then the alternate names become names for the backup file. If the old file is copied instead, then the alternate names remain names for the file that you are editing, and the contents accessed by those names will be the new contents.

See the linked page for further discussion.

Tyler
  • 21,719
  • 1
  • 52
  • 92