Symlink check - Linux Bash Script

陌路散爱 提交于 2019-12-24 00:53:47

问题


I'm trying to create a script that searches through a directory to find symlinks that point to non-existing objects.

I have a file in a directory with a deleted symlink, but for some reason when i run the below script It says file exists.

#!/bin/bash
ls -l $1 |
if [ -d $1 ]
  then
    while read file
    do
            if test -e $1
            then
                    echo "file exists"
            else
                    echo "file does not exist"
            fi
    done
 else
    echo "No directory given"
fi

Thanks


回答1:


Check this page. It has a test for broken links. It uses the -h operator to identify a symlink and the -e operator to check existance.

From that page:

linkchk () {
    for element in $1/*; do
      [ -h "$element" -a ! -e "$element" ] && echo \"$element\"
      [ -d "$element" ] && linkchk $element
    # Of course, '-h' tests for symbolic link, '-d' for directory.
    done
}

#  Send each arg that was passed to the script to the linkchk() function
#+ if it is a valid directoy.  If not, then print the error message
#+ and usage info.
##################
for directory in $directorys; do
    if [ -d $directory ]
    then linkchk $directory
    else 
        echo "$directory is not a directory"
        echo "Usage: $0 dir1 dir2 ..."
    fi
done

exit $?



回答2:


You can test whether link is valid or not using:

[[ -f "$link" ]] && echo "points to a valid file"

To check if it is indeed a link use -L:

[[ -L "$link" ]] && echo "it's a link"



回答3:


There seems to be a program named symlinks that does, among other things, what you're looking for.



来源:https://stackoverflow.com/questions/21676882/symlink-check-linux-bash-script

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