How to unlink file symlinked to itself without destroying
If a file is symlinked to itself then there's no data present and any attempt to access it will result in a loop, and ultimately an error
eg
$ ls -l myfile
lrwxrwxrwx 1 sweh sweh 19 Sep 9 22:38 myfile -> /path/to/here/myfile
$ cat myfile
cat: myfile: Too many levels of symbolic links
Since there's no data, deleting these symlinks won't lose any data, because there is no data to preserve.
If you don't get the Too many levels of symbolic links
error when you try to cat
the file then your file is not a link to itself.
ln
will never overwrite a file with a link to itself. You can get a file linked to itself with:
$ ln -s `pwd`/myfile myfile
$ ls -l myfile
lrwxrwxrwx 1 grochmal users 25 Sep 10 03:41 myfile -> /home/grochmal/tmp/myfile
But if you try with a file that contains data:
$ rm -f myfile
$ echo yay > myfile
$ ln -sf `pwd`/myfile myfile
ln: '/home/grochmal/tmp/myfile' and 'myfile' are the same file
ln
, on the other hand, will overwrite a file with a link to another file.
Yet, you can be rather sure that a link to itself is a file that never ever had data (or was explicitly deleted before the creation of the soft link).
(on Linux and using ln
from coreutils
, that is)