Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1278209
  • 博文数量: 213
  • 博客积分: 7590
  • 博客等级: 少将
  • 技术积分: 2185
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 17:31
个人简介

热爱开源,热爱linux

文章分类

全部博文(213)

文章存档

2018年(4)

2017年(1)

2015年(1)

2014年(5)

2013年(2)

2012年(2)

2011年(21)

2010年(82)

2009年(72)

2008年(23)

分类: LINUX

2010-08-12 19:44:15


以前有人让我帮忙写一个关于之拷贝一个目录中的子目录而不拷贝子目录中的文件,由于当时刚接触shell,没能写出来,今天写了一下,也参考了一些资料,现在基本功能已经能实现,具体代码如下:

#!/bin/bash
# Script name:cp_empty_dir.sh
#此脚本用于将源目录下的所有子目录复制到目的目录下,不复制源目录的文件,确保目的目录是空目录
usage()
{
    echo "Usage: ./cp_empty_dir.sh src_dir dest_dir"
}

#判断是不是两个参数,否则提示脚本用法
if [ $# -ne 2 ]; then
{
    usage
    exit 0
}
fi

src_dir=$1
dest_dir=$2

#判断源目录是不是目录,如果不是,提示错误信息及其用法
if [ ! -d $src_dir ];then
{
    usage
    echo " 错误,源目录${src_dir}不是目录"
    exit
}
fi
#判断目的目录是不是目录,如果不是,提示错误信息及其用法
if [ ! -d $src_dir ];then
{
    usage
    echo " 错误,目的目录${dest_dir}不是目录"
    exit
}
fi
#获得本身的id号
current_process_id=$$

#查找原目录下的所有子目录,输出并且保存到/tmp/${src_dir}_current_process_id.txt文件中
echo "源目录${src_dir}下的所有子目录"
echo "----------------------------------"
find $src_dir/* -type d| tee /tmp/${src_dir}_${current_process_id} #将所有子目录写到临时文件中
sed "s/^${src_dir}/${dest_dir}/g" /tmp/${src_dir}_${current_process_id} >/tmp/${src_dir}_tmp_${current_process_id}
#cat /tmp/${src_dir}_${current_process_id} #显示源目录中的所有子目录
#在目的目录下建立空子目录
rm -rf ${dest_dir}/*
for subdir in "`cat /tmp/${src_dir}_tmp_${current_process_id}`" #此处要建立的子目录保存在了临时文件中
do
    mkdir ${subdir}
done

#目的目录${dest_dir}下的所有子目录
echo "目的目录${dest_dir}下的所有子目录"
echo "----------------------------------"
find $dest_dir/* -type d| tee /tmp/${dest_dir}_${current_process_id}

#比较源目录与目的目录下子目录的差异
echo ""
echo "------------------------------------"
echo "比较源目录与目的目录下子目录的差异"
diff /tmp/${src_dir}_tmp_${current_process_id} /tmp/${dest_dir}_${current_process_id}

#删除辅助文件
rm -f /tmp/${src_dir}_tmp_${current_process_id}
rm -f /tmp/${src_dir}_${current_process_id}
rm -f /tmp/${dest_dir}_${current_process_id}


这样就能尽量减少手工建立目录不细心出现的的错误了
阅读(2476) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~