How to Remove All Symbolic Links with a Specific Target – Linux Tips

rmsymlinkwildcards

With the command:

ls -la *

I can list all my symbolic links.

How can I remove all symbolic links which are linked to a special folder?

For example:

In my directory usr/local/bin I have the following entries:

lrwxrwxrwx 1 root root 50 Apr 22 14:52 allneeded -> /usr/local/texlive/2011/bin/x86_64-linux/allneeded
lrwxrwxrwx 1 root root 47 Apr 22 14:52 amstex -> /usr/local/texlive/2011/bin/x86_64-linux/amstex
lrwxrwxrwx 1 root root 24 Apr 23 19:09 arara -> /home/marco/.arara/arara

Now I want to remove all links with the path /usr/local/texlive/

Best Answer

Please make sure to read the alternative answer. It's even more to the point although not voted as high at this point.

You can use this to delete all symbolic links:

find -type l -delete

with modern find versions.

On older find versions it may have to be:

find -type l -exec rm {} \;
# or
find -type l -exec unlink {} \;

To limit to a certain link target, assuming none of the paths contain any newline character:

 find -type l | while IFS= read -r lnkname; do if [ "$(readlink '$lnkname')" == "/your/exact/path" ]; then rm -- "$lnkname"; fi; done

or nicely formatted

 find -type l |
 while IFS= read -r lnkname;
 do
   if [ "$(readlink '$lnkname')" = "/your/exact/path" ];
   then
     rm -- "$lnkname"
   fi
 done

The if could of course also include a more complex condition such as matching a pattern with grep.


Tailored to your case:

find -type l | while IFS= read -r lnk; do if (readlink "$lnk" | grep -q '^/usr/local/texlive/'); then rm "$lnk"; fi; done

or nicely formatted:

find -type l | while IFS= read -r lnk
do
  if readlink "$lnk" | grep -q '^/usr/local/texlive/'
  then
    rm "$lnk"
  fi
done
Related Question