Unix: Why soft link file still pointing to original file when original file is deleted?

Posted on

Problem :

I have Windows 7 64-bit PC. I have installed Cygwin version 2.6.0 on it in c:cygwin64 directory.

I have a file named file1. For it I created a soft link file named file1_soft1.

ls -i -l command gives me this output:

total 2

3377699721198685 -rw-r–r– 1 cChappati Domain Users 57 Jan 20 19:47 file1
37154696926542763 lrwxrwxrwx 1 cChappati Domain Users 5 Jan 21 10:36 file1_soft1 -> file1

Then I deleted the original file using rm file1 command successfully.

Now when I run ls -i -l command, I get this output:

total 1
37154696926542763 lrwxrwxrwx 1 cChappati Domain Users 5 Jan 21
10:36 file1_soft1 -> file1

Why file1_soft1 file is still linked to file1 file when file1 file does not exist anymore?

I was expecting that either file1_soft1 file will also be deleted or become a regular file with soft link to file1 file removed. But none of this happened.

Thanks

Solution :

Why is file1_soft1 file is still linked to file1 file when file1 file does not exist anymore?

Windows file systems do not monitor links to see if the file linked to has been deleted.

Doing so would add some considerable overhead:

  • Maintaining a list of all links

  • Periodically checking the list to see if the file linked to has been deleted.

Windows:

  • The Windows commands used to create file soft links (mklink and shortcut) can both create links to non-existent targets.

Unix:

  • The Unix command to create soft links (ln -s) can also create links to non-existent targets.

    $ ll
    total 0
    $ ln -s target dummy
    $ ll
    total 1
    lrwxrwxrwx 1 DavidPostill None 6 Jan 21 16:19 dummy -> target
    $ cat dummy
    cat: dummy: No such file or directory
    $
    

    If you delete a file for which a symbolic link still exists, the rm will succeed but the symbolic link would remain and any attempt to reference it will return a ‘file not found’ error.


Further Reading

This is because soft link points to the path, not to the file itself.

Your assumption that the link is still pointing to the original file is wrong. It’s pointing to the original path.

It doesn’t matter what is there at this path nor if anything at all. If you create new file file1 (or maybe even a directory with that name) the link will point to it.

Leave a Reply

Your email address will not be published. Required fields are marked *