How to create a hard link to an inode (ext4)

hard linkinode

If I know the index node (inode) of a file, but I don't know its path (or any of its paths), is it possible to create a hard link to that inode directly?

I could find the file using sudo find / -inum 123546 and then create a hardlink, but that would be way too slow for my application.

N.B. I'm using an ext4 filesystem.

Best Answer

AFAIK, not with the kernel API. If such an interface existed, it would have to be limited to the super-user as otherwise that would let anyone access files in directories they don't have search access to.

But you could use debugfs on the file system (once it's unmounted) to do it (assuming you have write access to the block device).

debugfs -w /dev/block/device

(replace /dev/block/device with the actual block device the file system resides in).

Then, at the prompt of debugfs, enter

stat <123>
(with the angle brackets, replacing 123 with the actual inode number) to check that the file exists (inode has a link count greater than 0) and is not a directory.

If all good, enter:

ln <123> path/to/newfile
to create the hardlink (note that the path is relative to the root of the file system). Followed by:

mi <123>
to increment the link count (press Enter for all the fields except the link count where you'll want to add 1 to the current value).