5

First of all, I know that you can't create hardlinks of a folder.

I was wondering if there was any command (linux) that could automatically (and recursively) create the subsequent folder-tree at the destination and then hardlink all the files from source to destination automatically.

RazorHail
  • 212

2 Answers2

7

Would a bind mount be a better solution? It does exactly what you want, which is to have all the files be the same recursively at two different paths.

This command makes /other have the same contents as existing mount or directory /original:

mount --bind /original /other

Any changes you make in either /original or /other appear immediately in the other because the two paths are now pointers to the same mount.

Deltik
  • 19,971
7

I'm not sure what you mean by "then hardlink all the files from source to destination automatically". And you explicitly want recursion.

If you want the two locations to stay "synced", so e.g. removing or creating a file should be observed in both of them at once, then bind mounting (this other answer) is good. Note the solution leaves no trace in the filesystem. If you create a hardlink, it's created in the filesystem. Move the disk and mount the filesystem in another OS and the hardlink is still there. Reboot and the hardlink is still there. Bind mounts are on the OS level. Not only you would need to separately command the other OS to bind mount after you move and mount the disk. If you don't move the disk, you still need to tell the current OS to bind mount again after it reboots (if permanent solution is what you want).

A symlink to a directory is somewhat similar and it exists in the filesystem.

ln -s /original /other

If the symlink and its target belong to the same filesystem and the symlink is relative, then it will work even if the filesystem gets mounted elsewhere (different mountpoint, possibly in different OS). There are reasons a symlink may not be what you want (example).

Note bind mounting or symlinking is not really recursive. It's a single act that "links" two paths. It does nothing to deeper paths. Their (semi-)equivalence arises because there's some kind of link between respective ((((…)great-)great-)grand)parent "directories".

Now if by "then hardlink all the files from source to destination automatically" you mean "do this automatically but once", then you can do this with cp:

cp -lR /original /other

(-l is not required by POSIX though). It's like cp -R but with hardlinks. This is really recursive. But it's also one-time action. The directory subtrees are separate, only the regular files come up hardlinked. File creation or deletion will not be mirrored. Actions that break hardlinks will break hardlinks.