How can I detect whether a symlink is broken in Bash?
BashSymlinkBash Problem Overview
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
Bash Solutions
Solution 1 - Bash
# 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
Solution 2 - Bash
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 {} \;
Solution 3 - Bash
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
Solution 4 - Bash
This finds all files of type "link", which also resolves to a type "link". ie. a broken symlink
find /target -type l -xtype l
Solution 5 - Bash
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
Solution 6 - Bash
What's wrong with:
file $f | grep 'broken symbolic link'
Solution 7 - Bash
If it does qualify as a symbolic link, but is „not existing“, its a broken link.
if [[ -h $link && ! -e $link ]] ; then
_info "$link is a BROKEN SYMLINK"
fi