user8930130
user8930130

Reputation: 59

Can a hard link ever point to a deleted file?

I understand the different between hardlinks and softlinks in Linux, but I am having trouble understanding this one problem: Can a hard link ever point to a deleted file? Why or why not? I think it can but I am not certain. An explanation would be great. Thank you!

Upvotes: 3

Views: 10129

Answers (3)

iamauser
iamauser

Reputation: 11499

Consider an example,

 $ touch aFile.txt
 $ ls -i aFile.txt  # -i is the option to look at the inode of a file
 2621520 aFile.txt

 $ ln aFile.txt 2File.txt # Hardlink the file to another one
 $ ls -i 2File.txt
 2621520 2File.txt  # inode is pointing to the same location

 $ rm aFile.txt  # Original file gets deleted
 $ ls 2File.txt
 2File.txt

 $ ls -i 2File.txt # inode survives and still pointing to the same location
 2621520 2File.txt

Read here more on inodes.

EDIT: stat can show you the number of hardlinks of a file. You can use -c '%h' option to view that:

# after the hardlink to 2File.txt
$ stat -c '%h' aFile.txt 
2

Upvotes: 16

Yasushi Shoji
Yasushi Shoji

Reputation: 4292

A hard link will never point to a deleted file. A hard link is like a pointer to the actual file data. And the pointer is called "inode" in file system terminology. So, in other words, creating a hard link is creating another inode or a pointer to a file.

Having a pointer pointing to nothing is, useless at least, confusing. I mean, when you ls, you see files there. But if you're told "There is no such file" when you open it, your reaction would be "$#%*!@?"

Having data without a pointer is useless, too. Because there is no way you can open the file. You lost your handle to it but it's there. This happens when your HDD/SSD crashed and your file system is corrupted. A recovery tool might find file data with reference count zero, and place them, in the cases of EXT2, 3, 4, in the lost+found directory.

So, either cases, the Linux kernel doesn't allow you to create such links / inodes / pointers.

enter image description here

Upvotes: 0

Hard links are point to the same inode in the file system. I see like it a mirror, if you write into one of the hard links, the other will show the same information, at the end of the day you are writing in the same inode. Soft links are like in Windows the Shorcuts, if the original file is deleted the soft link get lost, and it is unusable. You already have a master answer with examples included, I hope you get it know. Kind Regards

Upvotes: 0

Related Questions