1

I have done the following operations:

  1. echo "test" >> t1
  2. echo "test2" >> t2
  3. ln t1 l1
  4. cp t2 t1
  5. cat l1

To my surprise after overwriting t1 with t2 the hard link was still working. As per my understanding when you create a new version of a file the hard link is not pointed to the new version.

Why after using the cat command on hard link [after overwriting] the hard link is still valid and pointing to the content of the new t1 file?

triple fault
  • 13,410
  • 8
  • 32
  • 45
  • this is strange indeed, I just did the same on OSX and got "test2" as the output of `cat l1` – p4sh4 Sep 01 '15 at 10:51

1 Answers1

1

According to the manpage of cp on OS X, this is intended behaviour:

-f

If the destination file cannot be opened, remove it and create a new file, without prompting for confirmation regardless of its permissions. (The -f option overrides any previous -n option.)

The target file is not unlinked before the copy. Thus, any existing access rights will be retained.

-n

Do not overwrite an existing file. (The -n option overrides any previous -f or -i options.)

Meaning that, removing the target file before copying is not done by default. The hard link will only break if one of the files is removed.

In order to consistently get the behaviour you are trying to achieve, you must remove the target file before copying.

jornane
  • 1,397
  • 10
  • 27
  • Can you please explain how this agrees with the following highly rated answer: http://askubuntu.com/questions/108771/what-is-the-difference-between-a-hard-link-and-a-symbolic-link – triple fault Sep 01 '15 at 11:01
  • "If you replace the other file with a new version (by copying it), a hardlink will not point to the new file." – triple fault Sep 01 '15 at 11:02
  • That must refer to `cp t2 t3` which makes that `t2` and `t3` are separate inodes. In your example, `t2` and `t1` are also different inodes. `t1` and `l1` are the same, though, even after the copy operation. – jornane Sep 01 '15 at 11:03
  • A bit confusing what @vartec means with "if you *replace*", the only way that makes sense is if you copy and then move over the original. – jornane Sep 01 '15 at 11:06