xinjiang 发表于 2018-8-20 10:19:58

Linux Shell Bash 文件测试操作符

1 #!/bin/bash  2 # broken-link.sh
  3 # 由Lee bigelow所编写
  4 # 已经争得作者的授权引用在本书中.
  5
  6 #一个纯粹的shell脚本用来找出那些断掉的符号链接文件并且输出它们所指向的文件.
  7 #以便于它们可以把输出提供给xargs来进行处理 :)
  8 #比如. broken-link.sh /somedir /someotherdir|xargs rm
  9 #
  10 #下边的方法, 不管怎么说, 都是一种更好的办法:
  11 #
  12 #find "somedir" -type l -print0|\
  13 #xargs -r0 file|\
  14 #grep "broken symbolic"|
  15 #sed -e 's/^\|: *broken symbolic.*$/"/g'
  16 #
  17 #但这不是一个纯粹的bash脚本, 最起码现在不是.
  18 #注意: 谨防在/proc文件系统和任何死循环链接中使用!
  19 ##############################################################
  20
  21
  22 #如果没有参数被传递到脚本中, 那么就使用
  23 #当前目录. 否则就是用传递进来的参数作为目录
  24 #来搜索.
  25 ####################
  26 [ $# -eq 0 ] && directorys=`pwd` || directorys=$@
  27
  28 #编写函数linkchk用来检查传递进来的目录或文件是否是链接,
  29 #并判断这些文件或目录是否存在. 然后打印它们所指向的文件.
  30 #如果传递进来的元素包含子目录,
  31 #那么把子目录也放到linkcheck函数中处理, 这样就达到了递归的目的.
  32 ##########
  33 linkchk () {
  34 for element in $1/*; do
  35 [ -h "$element" -a ! -e "$element" ] && echo \"$element\"
  36 [ -d "$element" ] && linkchk $element
  37 # 当然, '-h'用来测试符号链接, '-d'用来测试目录.
  38 done
  39 }
  40
  41 #把每个传递到脚本的参数都送到linkchk函数中进行处理,
  42 #检查是否有可用目录. 如果没有, 那么就打印错误消息和
  43 #使用信息.
  44 ################
  45 for directory in $directorys; do
  46 if [ -d $directory ]
  47 then linkchk $directory
  48 else
  49 echo "$directory is not a directory"
  50 echo "Usage: $0 dir1 dir2 ..."
  51 fi
  52 done
  53
  54 exit 0


页: [1]
查看完整版本: Linux Shell Bash 文件测试操作符