Search code examples
linuxsymlinkhardlink

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!


Solution

  • 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