2012-03-27 48 views

回答

2

以下bash脚本会发现在当前目录中的所有环节,确定的目标路径是否存在:

for i in $(find . -type l -mindepth 1 -maxdepth 1); do 
    links_to=$(readlink $i); 
    echo -n "$i links to $links_to and that path "; 
    if [[ -e $links_to ]]; then 
    echo "exists"; 
    else 
    echo "does not exist" 
    fi 
done; 

实例目录:

$ ls -l 
total 2 
-rw-r--r-- 1 user staff  0 Sep 26 14:54 a_file 
lrwxr-xr-x 1 user staff 14 Sep 26 14:50 no_target -> does_not_exist 
lrwxr-xr-x 1 user staff 21 Aug 13 14:50 has_target -> a_file 

输出示例:

./no_target links to does_not_exist and that path does not exist 
./sources links to a_file and that path exists 

键盘命令使用find过滤掉当前目录中不是链接的任何东西,并使用readlink来确定链接的目标。

注: 某些系统没有readlink命令。 在这种情况下,你可能想尝试添加以下bash函数顶端:在上面的脚本

my_readlink() { ls -ld "$1" | sed 's/.*-> //'; } 

和2行改为调用该函数:

links_to=$(my_readlink $i) 

但这通常是不太理想,因为你正在解析输出为ls -ld,这是较慢和更容易出错的。

+0

慎用'-depth';在BSD中只有一个参数找到。 GNU find需要使用“-mindepth”和“-maxdepth”谓词。 – 2012-09-26 19:12:18

+0

Ignacio - 谢谢,修正。 – mwolfetech 2012-09-26 19:31:35

0

bash这将打印照片,无需目标的所有符号链接:

for f in $(find . -mount -type l) 
do 
    [ ! -e "$f" ] && echo "$f" 
done 
相关问题