How can I detect whether a symlink is broken in 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

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

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 {} \;

Tags:

Bash

Symlink