写一个复制文件夹的脚本.
原理:先把要复制的文件夹用tar进行打包,然后把该包复制过去,再解包.
接收两个参数,当参数小于2时会报错.
如果目标文件夹不是一个文件夹,也会报错.
如果源文件(夹)不存在,也会报错.
然后提取要复制的文件(夹),如:/home/user1/test,则会提取test,
然后把该文件(夹)进行tar打包.
把该包传到目标文件夹,再解包.并把中间文件(由tar生成)删除.
CODE:
#!/bin/sh
# cpdir source_dir target_dir
# author hjack
# date:2006.3.25
# copy dir
#########variables define##########
SOURCE_DIR=$1
TARGET_DIR=$2
CURRENT_DIR=`pwd`
SOURCE_FILE=""
#########main start here###########
##check the argements.
if [ $# -lt 2 ]; then
echo "request more arguments."
exit
fi
##does the target dir exist?
if [ ! -d $TARGET_DIR ]; then
echo "not such dir."
exit
fi
if [ -e $SOURCE_DIR ] ; then
##sourcedir string ends with '/'.
echo $SOURCE_DIR | grep /$ >/dev/null
if [ $? -eq 0 ];then
##get the file or dir name.eg:/home/user1/test,it will get test.
SOURCE_FILE=$(echo $SOURCE_DIR | awk -F/ '{print$(NF-1)}')
else
SOURCE_FILE=$(echo $SOURCE_DIR | awk -F/ '{print$NF}')
fi
else
echo "not such dir."
exit
fi
##first,compress the dir.
tempFile="tmp.cpdir.0123456789".$SOURCE_FILE".tgz"
tar zcf $tempFile $SOURCE_FILE
#then ,decompress the tar file.
mv $tempFile $TARGET_DIR
cd $TARGET_DIR
tar zxf $tempFile
rm $tempFile
cd $CURRENT_DIR
echo "copy finished."
# cpdir source_dir target_dir
# author hjack
# date:2006.3.25
# copy dir
#########variables define##########
SOURCE_DIR=$1
TARGET_DIR=$2
CURRENT_DIR=`pwd`
SOURCE_FILE=""
#########main start here###########
##check the argements.
if [ $# -lt 2 ]; then
echo "request more arguments."
exit
fi
##does the target dir exist?
if [ ! -d $TARGET_DIR ]; then
echo "not such dir."
exit
fi
if [ -e $SOURCE_DIR ] ; then
##sourcedir string ends with '/'.
echo $SOURCE_DIR | grep /$ >/dev/null
if [ $? -eq 0 ];then
##get the file or dir name.eg:/home/user1/test,it will get test.
SOURCE_FILE=$(echo $SOURCE_DIR | awk -F/ '{print$(NF-1)}')
else
SOURCE_FILE=$(echo $SOURCE_DIR | awk -F/ '{print$NF}')
fi
else
echo "not such dir."
exit
fi
##first,compress the dir.
tempFile="tmp.cpdir.0123456789".$SOURCE_FILE".tgz"
tar zcf $tempFile $SOURCE_FILE
#then ,decompress the tar file.
mv $tempFile $TARGET_DIR
cd $TARGET_DIR
tar zxf $tempFile
rm $tempFile
cd $CURRENT_DIR
echo "copy finished."
注解:
$#表示命令参数个数.
[ -d $TARGET_DIR ] 测试目标文件夹是否是一个文件夹.
[ $? -eq 0 ]测试上一条命令的是否执行成功.
$?是上一条命令的返回码.
tar 打包命令.