19

I am implementing a backup scheme using rsync and hardlinks. I know I can use link-dest with rsync to do the hardlinks, but I saw mention of using "cp -l" before "link-dest" was implemented in rsync. Another method of hardlinking I know of is "ln".

So my question is, out of curiosity: is there a difference in making hardlinks using "cp -l" as compared to using "ln"?

twan163
  • 5,690

2 Answers2

23

The results of both has to be the same, in that a hard link is created to the original file.

The difference is in the intended usage and therefore the options available to each command. For example, cp can use recursion whereas ln cannot:

cp -lr <src> <target>

will create hard links in <target> to all files in <src>. (it creates new directories; not links) The result will be that the directory tree structure under <target> will look identical to the one under <src>. It will differ from cp -r <src> <target> in that using the latter will copy each file and folder and give each a new inode whereas the former just uses hard links on files and therefore simply increases their Links count.

When used to copy a single file, as in your example, then the results will be the identical.

garethTheRed
  • 33,957
  • 1
    if I understand correctly, "cp -lr" will create hardlinks for all the files, but if there are missing directories in , these will be created as new (i.e. no hardlinks to directories in )? – twan163 Aug 09 '14 at 14:46
  • 1
    Yes, that's correct. You cannot create hard links to directories. Therefore in order to keep the file/directory structure, it becomes hard-links for files inside 'real' directories. – garethTheRed Aug 09 '14 at 16:49
  • regarding the behavior for "cp -lr": hardlinks for files... new directories for directories. seems a little strange but I guess this "strange" behavior is a side effect of the constraints (can't have hardlinks of directories). ||| also FYI for reference here's some links to info on hardlinks not allowed for directoreis ref1 from askubuntu and ref2 from unix.stackexchange. – Trevor Boyd Smith Feb 15 '17 at 12:26
7

link uses the least system calls, followed by ln and finally cp:

$ strace link f.txt g.txt | wc --lines
282

$ strace ln --symbolic f.txt g.txt | wc --lines
311

$ strace ln f.txt g.txt | wc --lines
334

$ strace cp --symbolic f.txt g.txt | wc --lines
394

$ strace cp --link f.txt g.txt | wc --lines
410
Zombo
  • 1
  • 5
  • 44
  • 63