Chinaunix首页 | 论坛 | 博客
  • 博客访问: 667425
  • 博文数量: 467
  • 博客积分: 8050
  • 博客等级: 中将
  • 技术积分: 14825
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-18 11:00
文章分类

全部博文(467)

文章存档

2009年(8)

2008年(459)

分类:

2008-12-21 01:54:14



由youyu_buzai发贴所提需求,写了个自动从备份目录向保护目录恢复文件的shell,其中用了不少技巧,希望对大家有所帮助。
大家看看是否值得值得加精或保留?
需求见:[url][/url]
在linux调试通过:


cat autorestore.sh
#!/bin/ksh
#定义目录变量,要用绝对路径,不要在尾部加/
#备份目录
dirs=/tmp/dirs
#被保护目录
dird=/tmp/dird
#间隔秒数
times=20

if [ "${0#/}" = "${0}" ]
then
   echo "请使用绝对路径!"
   exit 1
fi

case "$1" in
-enable)
   ps -ef|awk '$2!=0'$$' && ( $9=="'$0'" && $10=="-start"||
               $9~"sh" && $10=="'$0'" && $11=="-start" ) {system("set -x;kill -9 "$2);}'
   sed  -i  '/^[^#][^:]\+:[0-9]\+:[^:]\+:\/bin\/autorestore.sh/d;$a\
arst:234:respawn:/bin/autorestore.sh -start
' /etc/inittab
   init q
   echo "在/etc/inittab中插入自动运行$0"
   exit 0
;;
-disable)
   sed  -i  '/^[^#][^:]\+:[0-9]\+:[^:]\+:\/bin\/autorestore.sh/d' /etc/inittab
   init q
   sleep 3
   ps -ef|awk '$2!=0'$$' && ( $9=="'$0'" && $10=="-start"||
               $9~"sh" && $10=="'$0'" && $11=="-start" ) {system("set -x;kill -9 "$2);}'
   echo "停止/etc/inittab中自动运行$0"
   exit 0
;;
-stop)
   ps -ef|awk '$2!=0'$$' && ( $9=="'$0'" && $10=="-start"||
               $9~"sh" && $10=="'$0'" && $11=="-start" ) {system("set -x;kill -9 "$2);}'
   echo "停止$0"
   exit 0
;;
-start)
   ps -f -C $0|awk '$3==1 && $2!=0'$$' {system("set -x;kill -9 "$2);}'
   echo "开始自动备份$0"
;;
*)
   echo "
自动从备份目录${dirs}向被保护目录恢复${dird}恢复文件,间隔时间:$times
用法:
提交到/etc/inittab自动运行:
        $0 -enable
取消/etc/inittab中的自动运行:
        $0 -disable
手工运行:
        $0 -start
停止运行:
        $0 -stop
"
exit 1
esac

#无限循环
while [ 1 = 1 ]
do

  cd $dird
  #列被保护目录,包含子子目录、长格式、符号链接显示文件信息、按名子排序、日期全格式
  ls -RlL --full-time >/tmp/filelistd.txt
  cd $dirs
  #列备份目录,包含子子目录、长格式、符号链接显示文件信息、按名子排序、日期全格式
  ls -RlL --full-time >/tmp/filelists.txt
  if [ -s /tmp/filelistcp.txt ]
  then
    rm /tmp/filelistcp.txt
  fi
  gawk  '{
#     print "DBG",NR,FNR,$0;
#找.目录名:  
     if (match($0,"^(\..*):$",a)){
#记下目录名
          dir=a[1];
     }else{
#-开头的是文件,其它的就跳过
          if($1~"^-" && NF>=9) {
                 if (NR==FNR){
#备份目录,记下大小及目录,存在数组filesztm中
                         filesztm[ dir "/" $9]=$5 " " $6 " " $7;
                 } else {
#被保护目录,与存在数组filesztm中比较大小及日期,相同就从数组中删除
                         if (filesztm[ dir "/" $9]==($5 " " $6 " " $7))
                               {delete filesztm[ dir "/" $9];}
                 }
          }
     }
  }
  END{
#生成需要恢复的文件清单(2008.12.19注:下面的for循环中原来用i作变量名,论坛中显示有问题,现改为ii作变量)
     for (ii in filesztm){
        if (filesztm[ii]!=""){
            print ii >>"/tmp/filelistcp.txt";
         }
     }
  }' /tmp/filelists.txt /tmp/filelistd.txt
  if [ -s /tmp/filelistcp.txt ]
  then
#从备份目录恢复文件
     cpio -uvdmp "$dird"   fi
#延时
  sleep $times
done
阅读(699) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~