Have several hardlinks to the same file.
How (for example) by one file(hardlink) get others pointing to the same data?
No real task. Just interesting. May be useful.
-
The question is the answer. What did you actually mean to ask? How to create hard links? What hard links are and how they work? What are hard links used for? Lots of these questions have already been asked and answered.– JdeBPJun 22, 2011 at 9:13
2 Answers
Most filesystems do not maintain a directory of where the hardlinks to a file (or more precisely, to an indode) are.
So you'll have to scan the whole filesystem to find all hardlinks. You can do this using find -inum <inode number>
.
Example:
Create file with link:
$ ~> mkdir linktest
$ ~> cd linktest/
$ ~/linktest> touch file1
$ ~/linktest> ln file1 file2
Check inodes:
$ ~/linktest> stat file*
File: file1
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: 805h/2053d Inode: 37 Links: 2
[...]
File: file2
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: 805h/2053d Inode: 37 Links: 2
[...]
As you can see, both file entries have the same inode (37) - because they are hardlinks to the same data.
Find by inode number:
$ ~/linktest> find -inum 37
./file1
./file2
This is on Linux, but it should work the same on *BSD.
find
has an option -samefile
for this:
find / -xdev -samefile /myfile
Replace /
with the root of the filesystem that myfile
is on – for example, if you used /home/sergey/myfile
and you have /home
on a separate filesystem, then use find /home
.