If you have a big project with multiple shared libraries, there is a chance to run into soft links that are no longer pointing anywhere. Here are couple of ways to find those dangling soft links that no longer point to any real file using the Unix find command.
These are in preferred order.
find /path/to/search -type l | (while read FN ; do /usr/bin/test -e "$FN" || echo "$FN"; done) find /path/to/search -type l ! -exec /usr/bin/test -r {} ; -print find -L /path/to/search -type l
So here is how these can be used to clean out those dangling soft links (again in preferred order). We use rm to ensure that any aliases don’t kick in. First one is the best way which is portable to most Unix platforms.
find /path/to/search -type l | (while read FN ; do /usr/bin/test -e "$FN" || rm -f "$FN"; done) find -L /path/to/search -type l -exec rm -f {} ; find -L /path/to/search -type l -delete
Note: When using in script, make sure to escape the properly.
Interoperability Issues between SunOS and Linux
-delete is not supported on SunOS find. It is available on GNU findutils. So using -exec to invoke rm command would be portable. As well as the test for existence /usr/bin/test -e is portable. Make sure to use /usr/bin/test instead of shell built in test because on sh the flag -e is not available.
Update (2011-08-12) : /usr/bin/test should be used for interoperability.
Using the “-L” parm with find can be troublesome in certain cases. Details are on StackExchange at:
http://unix.stackexchange.com/questions/34248/how-can-i-find-broken-symlinks/38691#38691
Personally I’d use find to generate a list, then manually review the list and decide what to delete. If my system is suddenly getting a ton of new broken symlinks, it’s probably a symptom of some deeper problem.
A perl script to list dead symlinks.
http://www.notnull.ro/log/find-dead-links-on-unix-with-perl/
It also taking care about the cycles that can be present on the tree directory structure.