寫一個複製檔案夾的指令碼.
原理:先把要複製的檔案夾用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."
註解:
$#表示命令參數個數.
[ -d $TARGET_DIR ] 測試目標檔案夾是否是一個檔案夾.
[ $? -eq 0 ]測試上一條命令的是否執行成功.
$?是上一條命令的返回碼.
tar 打包命令.