I run find
and iterate through the results with [ \( -L $F \) ]
to collect certain symbolic links.
I am wondering if there is an easy way to determine if the link is broken (points to a non-existent file) in this scenario.
Here is my code:
FILES=`find /target/ | grep -v '\.disabled$' | sort`
for F in $FILES; do
if [ -L $F ]; then
DO THINGS
fi
done
# test if symlink is broken (by seeing if it links to an existing file)
if [ ! -e "$F" ] ; then
# code if the symlink is broken
fi
This should print out links that are broken:
find /target/dir -type l ! -exec test -e {} \; -print
You can also chain in operations to find
command, e.g. deleting the broken link:
find /target/dir -type l ! -exec test -e {} \; -exec rm {} \;
this will work if the symlink was pointing to a file or a directory, but now is broken
if [[ -L "$strFile" ]] && [[ ! -a "$strFile" ]];then
echo "'$strFile' is a broken symlink";
fi
readlink -q
will fail silently if the link is bad:
for F in $FILES; do
if [ -L $F ]; then
if readlink -q $F >/dev/null ; then
DO THINGS
else
echo "$F: bad link" >/dev/stderr
fi
fi
done
This finds all files of type "link", which also resolves to a type "link". ie. a broken symlink
find /target -type l -xtype l
If you don't mind traversing non-broken dir symlinks, to find all orphaned links:
$ find -L /target -type l | while read -r file; do echo $file is orphaned; done
To find all files that are not orphaned links:
$ find -L /target ! -type l
What's wrong with:
file $f | grep 'broken symbolic link'