How can I detect whether a symlink is broken in Ba

2020-02-17 10:08发布

问题:

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

回答1:

# 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


回答2:

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


回答3:

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


回答4:

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


回答5:

This finds all files of type "link", which also resolves to a type "link". ie. a broken symlink

find /target -type l -xtype l


回答6:

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


回答7:

What's wrong with:

file $f | grep 'broken symbolic link'



标签: bash symlink