1

I've seen people on the internet talk about using hardlinks to force files to stay on disk as a backup, even if they're deleted in their original location.

Would this work for a directory too? Why or why not?

Assume that I'm using an ext4 filesystem, if it matters, but I'd also be interested in answers for other (UNIX/inode-based) filesystems, especially btrfs.

strugee
  • 14,951

1 Answers1

3

It would not work.

A hard link does not preserve the contents of files, just the pointer to those contents. So in case of files, file modifications are not preserved, and for directories that means changes in the contents of directories would not be preserved either. As (down under) each file is deleted individually. Even if you could hard link a directory, it would just be empty afterwards all the same.

Hardlinks are usually disallowed for directories in the first place. Symlinks for directories are already problematic, there are hacks in place to prevent a infinite symlink loop to be followed down to deep. At least for symlinks they're easily identified and simply ignored, most programs that walk directory trees (such as find) ignore them completely (never follow them) by default.

Hardlinked directories would be harder to detect and keep track of, as you cannot tell which one you already visited, you'd have to check for each directory whether it's one of the already visited ones. Most programs don't do this as they simply expect that by convention this thing does not exist in the first place.

If you still need to hardlink directories for some reason, there is something that does something very similar, and that's mount --bind olddir newdir. Bind mounts do not have some of the pitfalls, e.g. no infinite structures as the mount is locked to one place and does not repeat unto itself. In exchange it has others (other submounts do not appear in this tree either). Which is a great feature if you're looking for files hidden by other mounts.

There is no preservation of contents in either case, for that you always need a real copy.

frostschutz
  • 48,978
  • 1
    a hardlink does save the file if the file is deleted at its original location, because the inode still has a reference so it can't be deallocated. – strugee Sep 05 '13 at 06:47
  • 1
    also, bind mounts won't persist across reboots, if you just typed that out verbatim without adding it to the fstab or something. – strugee Sep 05 '13 at 06:49
  • 1
    @strugee But you can't delete a directory unless it's empty. So the hardlinked directory would indeed be preserved if it were deleted in the original location, but since it would have been empty that's not much protection. – Barmar Dec 12 '14 at 22:58