本文所选的例子来自于《Advanced Bash-scripting Gudie》一书,译者 杨春敏 黄毅
1 #/bin/bash
2 #用一个纯粹的shell脚本来找出坏链接文件
3 #什么是broken link?对于符号链接(软链接),如果先删除原文件,则会成为坏链接(broken link)
4
5 方法一
6 find "somedir" -type l -print0 | xargs -r0 file | grep "broken symbolic" | sed -e 's/^\|: *broken symbolic.*$/''/g'
7 #这并不是一个纯粹的shell脚本
8 #-type l 文件类型为符号链接的文件
9 #file命令用来识别文件类型,也可用来辨别一些文件的编码格式
10 #如果文件是“broken link",那么find . -type l -print0 | xargs -r0 file执行后就会显示如下:./yum.log.soft: broken symbolic link to `/tmp/yum.log'
11
12 #\| 是一个出现在样式内部并经过转义的定界符
13 #当定界符号出现在样式内部时,我们必须用前缀\对它进行转义
14 #sed 's:text:replace:g'
15 #sed 's|text|replace|g'
16 #sed 's|te\|xt|replace|g'
17
18 #例子:
19 #echo 123:thisthisthis | sed -e 's/^\|:*this.*$/''/g'
20 #123
21 #echo 123:abcthisthisthis | sed -e 's/|:.*this.*/''/g'
22 #123 注意两者的区别,即":"后有无"."
23
24 方法二:
25 #!/bin/bash
26
27 #检查目录是否传入参数,如果没有传入参数,就以当前目录作为搜索目录,
28 #如果有传入的参数,以传入参数的目录作为搜索目录
29 # 其实这个$@是不可以改成$1的,有很多位置参数的情况还是存在的,换成$1只对第一个位置参数有效
30 if [ $# -eq 0 ]
31 then
32 directorys=`pwd`
33 else
34 directorys=$@
35 fi
36
37 #$1指的就是$directory,第一个位置参数,$1/*指的是$1下所有的目录和文件
38 #这部分主要针对目录下的目录而言,如果$directory下还有一个目录,那么把整个目录作为位置参数传入linkchk函数,如果下面还有,再作为位置参数传入,这是递归的
39 #-h 检查符号链接文件是否存在(存在为真),! -e 检查文件是否不存在(不存在为真),这两个同时要成立是不是前后矛盾?
40 #经检查,发现不是这样,cat 坏链接名,会提示没有那个文件或目录,说明链接文件指向的原文件的值已不存在,其属性还在
41 linkchk()
42 {
43 for i in $1/*
44 do
45 if [ -h "$i" -a ! -e "$i" ]
46 then
47 echo "$i"
48 elif [ -d "$i" ]
49 then
50 linkchk "$i"
51 fi
52 done
53 }
54
55 #linkchk()是一个自定义的函数,$directory是这个函数中传入的第一个位置参数
56 for directory in $directorys
57 do
58 if [ -d $directory ]
59 then
60 linkchk $directory
61 else
62 echo "$directory is not a directory"
63 echo "Usage: $0 dir1 dir2 ..."
64 fi
65 done
66
67 exit 0
脚本运行结果