Deleting a broken link Unix

丶灬走出姿态 提交于 2020-01-14 13:39:07

问题


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?


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/3637952/deleting-a-broken-link-unix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!