37

I have a file in ~/file.txt.

I have created a hard link by :

ln ~/file.txt ~/test/hardfile.txt

and a symlink file :

ln -s ~/file.txt ~/test/symfile.txt

Now,

  1. How can I find out that which file is hard link ?
  2. How can I find out hard link follows which file?

We can find symlink file by ->, but what about hard link?

enter image description here

  • @kasperd, They are almost similar. But this one just asks how to find if a file is a hard link or symbolic link while the one you are referring says how could we find it in a script. There is some ambiguity but I feel both the questions can be merged. – Ramesh Nov 28 '14 at 15:55
  • 1
    A hard link is not a link but a name for the file itself. – 炸鱼薯条德里克 Sep 21 '19 at 15:37

2 Answers2

52
-rw--r--r-- 2 kamix users 5 Nov 17:10 hardfile.txt
            ^

That's the number of hard links the file has. A "hard link" is actually between two directory entries; they're really the same file. You can tell by looking at the output from stat:

stat hardfile.txt | grep -i inode
Device: 805h/2053d      Inode: 1835019     Links: 2

Notice again the number of links is 2, indicating there's another listing for this file somewhere. The reason you know this is the same file as another is they have the same inode number; no other file will have that. Unfortunately, this is the only way to find them (by inode number).

There are some ideas about how best to find a file by inode (e.g., with find) in this Q&A.

damd
  • 105
  • 3
goldilocks
  • 87,661
  • 30
  • 204
  • 262
8

A hard linked file has more than one link (the 2 after the permission flags). You can use the stat command to easily extract this information:

$ stat --printf '%h\n' hardfile.txt
2

See the manpage for stat (man 1 stat) for information about other values and how to print them.

wurtel
  • 16,115