开发者

Deleting a broken link Unix

I want to delete a broken link, but before that I want to confirm if the link file is pre开发者_StackOverflow中文版sent 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?


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)" ]
}


if readlink -qe A > /dev/null; then
    echo "link works"
fi


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜