A perennial problem for the diligent systems admin is occurrence of "dead" symbolic links. These are files with a text string giving the name and path to another file which no longer exists. The OS automatically follows the link which generates an error.
I have seen many discussion and help sites which assert, correctly, that links may be found with the find command as in
cd /tmp # mkdir test # cd test # touch bar # ln -s bar foo # find ./ -type l print foo
Fair enough but this will find all the symbolic links when what we want is just the broken ones.
We can take the list of symbolic links and check for broken links by using test to check if the file exists (remember the OS will automatically follow the link).e.g.
# rm bar # find ./ -type l -print | > while read f ;do > [ -e $f ]|| echo "$f is a broken link" >&2 > done
An alternative and probably quicker way, is to tell find to follow symbolic links which, with a logic that I confess defeats me, returns true if the link is broken.
# rm bar # touch b # ln -s b a # find -L ./ -type l -print ./foo
Now we have to remove the link file. We can do this by piping the output to a script
# find -L ./ -type l -print| > while read f;do > rm $f > done # ls a@ b
or more briefly using xargs
# find -L ./ -type l |xargs rm
or, simplest of all, using the deleteaction within find.
find -L ./ -type l -delete
Unbelievably easy when you know ain’t it?
I have a script called chklnks that can check for broken links, report, log and optionally remove them as part of the routine cleaning process.
Clifford W Fulford
29 February 2016.
Copyright
© 2003-2018
Clifford W Fulford.
Fulford Consulting Ltd.
Regd. Co. 4250037 in England & Wales.
Regd. office 162, Edward Rd. Nottingham NG2 5GF, England, UK.
Related sites;
Amharic Interpreter
|
Arabic Interpreter
|
Tigrinya Interpreter
|
Joan Mary Fulford
|
Linux Training
|
Flare Support
|
Fulford Consulting Ltd.
Fulford Portal
West Bridgford Wiki
The layout and associated style sheets for this page are taken from the World Wide Web Consortium and used here under the W3C software licence.