Editing softlinked files in UNIX

3

1

Let's say I have file A, and using 'ln -s A B', I have B.

When I open, edit and save B, now B is not symlink anymore. It's just a new copy of A.

  • Is this expected behavior? I use Mac OS X, and I wonder it's common in UNIX.
  • In this case, is there any way to keep B as a (soft link) to A? Or, make B as the hard link would be the only way to solve this issue?
  • What's the advantage of using soft link than hard link?

ADDED

The editor that I use is 'TextMate' on Mac.

prosseek

Posted 2010-09-02T02:39:04.023

Reputation: 4 635

What editor are you using? – Jason Axelson – 2010-09-02T03:44:03.947

Report a bug in the editor - not nice behaviour. – Jonathan Leffler – 2010-09-02T04:49:44.907

Answers

6

This happens when the editor saves to a temporary file, removes the original, then renames the temporary file. Not all editors follow this behavior, but most do for reliability reasons. And making it a hard link won't help since the link would be erased regardless.

Ignacio Vazquez-Abrams

Posted 2010-09-02T02:39:04.023

Reputation: 100 516

If the editor in question is emacs the behavior can be turned off, but it does that for a pretty good reason and you should think before canceling it. – dmckee --- ex-moderator kitten – 2010-09-02T03:04:08.027

1I do this all the time with VIM, and the links don't get broken. – Nathan Fellman – 2010-09-02T03:21:04.287

@Nathan as Ignacio stated not all editors follow this behaviour. vim does not. – matthias krull – 2010-09-02T09:31:46.887

@mugen: I know. I was not trying to contradict him, but rather to suggest one editor that does work well with links. – Nathan Fellman – 2010-09-02T12:41:02.967

@Nathan: vim usually follows the method described by Ignacio (which reduces the potential damage if something bad happens while saving the file, like a full disk or a power failure: this method guarantees that you will have at least either the old or the new version of the file, and the change is atomic). But when it figures that this method would have bad side effects (symbolic link, file with hard links, unwritable directory, …), vim modifies the file directly. – Gilles 'SO- stop being evil' – 2010-09-02T17:51:30.993

@dmckee: Emacs does mostly the same as vim, with one improvement: if you open a file via a symbolic link, it still uses the robust create-new-and-move method (but it does this on the target file, not on the link). – Gilles 'SO- stop being evil' – 2010-09-02T17:54:13.840

@Gilles: Must have changed since the last time I got bit by it. (Well, minor bite because no data was lost, just another program not noticing the update for a while, but it caused confusion.) 'Course I think that was major version 19 or there abouts... – dmckee --- ex-moderator kitten – 2010-09-20T00:36:31.227