If I create a file and symlink to it e.g
touch "example"
ln -s "example" "link_example"
and use
rm example
the symlink is still there. How can I delete file and all symlinks that points to that file with it?
If I create a file and symlink to it e.g
touch "example"
ln -s "example" "link_example"
and use
rm example
the symlink is still there. How can I delete file and all symlinks that points to that file with it?
There's no link from a file to symlinks that point to it, so there's no direct way of considering example
and finding link_example
which links to it. So deleting symlinks pointing to a file along with the file involves finding all the symlinks first.
You don't specify what system you're using, but if you have GNU find
, you can delete a file and its links with
find -L / -samefile example -delete
You might want to run
find -L / -samefile example
first to list what will be deleted.
This instructs find
to follow symlinks (-L
), start from /
, and report any file which resolves to the same inode as example
— so this will match hard and soft links to example
as well as example
itself.
Alternatively, using only POSIX find
, you can delete example
and then look for broken symlinks:
rm example
find -L / -type l
If you're sure all the results should be deleted:
find -L / -type l -exec rm {} +
will delete all the broken symlinks (in directories you can write to).