12

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..

  • 3
    Ok, I think I found the solution: If I add (setq backup-by-copying t) to my ~/.emacs init file it works as desired.. – Håkon Hægland Dec 9 '14 at 12:22
10

@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.

  • 2
    Note that you can set this as a file local variable, in case you don't want this behaviour for all files. – Harald Hanche-Olsen Dec 9 '14 at 15:46
  • @HaraldHanche-Olsen noted! – Tyler Dec 9 '14 at 19:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.