4

I want to delete a broken link, but before that I want to confirm if the link file is present in directory. Let's call the link A:

if [ -a A ] then 
  print 'ya A is ther'
fi

But if A is a broken link then how can I check?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Black Diamond
  • 361
  • 5
  • 16

3 Answers3

4

find -L -type l finds broken symbolic links. First confirm that the file is not a directory or a symbolic link to a directory with test -d (if it's a directory, find would recurse into it). Thus:

is_broken_symlink () {
    case $1 in -*) set "./$1";; esac
    ! [ -d "$1" ] && [ -n "$(find -L "$1" -type l)" ]
}

This is prone to a race condition, if the link changes between the call to test and the call to find. An alternative approach is to tell find not to recurse.

is_broken_symlink () {
    case $1 in -*) set "./$1";; esac
    [ -n "$(find -L "$1" -type l -print -o -prune)" ]
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
2
if readlink -qe A > /dev/null; then
    echo "link works"
fi
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

Look at example 7-4 of this page: Testing for broken links.

John Carter
  • 53,924
  • 26
  • 111
  • 144