2014-02-10 44 views
1

我试图创建一个脚本,通过搜索目录来查找指向不存在的对象的符号链接。符号链接检查 - Linux Bash脚本

我有一个文件在一个删除符号链接的目录,但由于某种原因,当我运行下面的脚本它说文件存在。

#!/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 

感谢

回答

3

检查this page。它有一个测试断链。它使用-h运算符来识别符号链接,并使用-e运算符来检查存在。

在这个页面:

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 $? 
0

似乎有一个名为symlinks程序,做,除其他事项外,你在找什么。

2

您可以测试链接是否有效或者是不使用:

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

要检查,如果它确实是一个链接使用-L

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