1. 程式人生 > 其它 >比較2個目錄找出不同的檔案

比較2個目錄找出不同的檔案

技術標籤:shellshell

#!/bin/bash
function filter_in()
{
	res=0
	if [[ -z "${1}" || "${1}" == "*" ]];then
		echo "1"
		return 
	fi
	
	for n in ${1}
	do
		if [[ "${2}" = *"${n}" ]];then  #單"[]"不能使用萬用字元  
			res=1
			break
		fi
	done 
	
	echo "${res}"	
}

function filter_out()
{
	res=0
	if [[ -z "${1}" ]];then
		echo "0"
		exit
	fi
	
	for n in ${1}
	do
		if [[ "${2}" = *"${n}" ]];then  #單"[]"不能使用萬用字元			
			res=1
			break
		fi
	done 
	
	echo "${res}"	
}

function process_dir()
{
	echo "dir:${1}"
	
}

function process_file()
{	
	if [[ $(filter_in "${2}" "${1}/${file}") != 1 ||  $(filter_out "${3}" "${1}/${file}") == 1 ]];then		
		return		
	fi
	file_new=${1}
	file_old="${DIR_OLD}"/"${file_new:((DIR_NEW_LEN+1))}"
	if [ -e ${file_old} ];then
		diff ${file_new} ${file_old} > /dev/null
		if [ $? != 0 ];then
			let DIFF_FILE_CNT++
			if [ -n "${DIR_DIFF_NEW}" ];then 
				out_dir=${DIR_DIFF_NEW}/${file_new:((DIR_NEW_LEN+1))}
				out_dir=${out_dir%/*}  #使用萬用字元截斷字串		
				if [ ! -e "${out_dir}" ];then
					echo "mkdir -p ${out_dir}"
				fi
				echo "cp -rf ${file_new} ${DIR_DIFF_NEW}/${file_new:((DIR_NEW_LEN+1))}"	
			else
				echo "diff(${DIFF_FILE_CNT}):${file_new}    ${file_old}"		
			fi						
		fi
		
	fi
}

function traverse_directory()
{
	f=$(ls ${1})	
	for file in ${f}
	do 
		if [ -d "${1}/${file}" ];then 	
			#process_dir	"${1}/${file}"	
			traverse_directory "${1}/${file}" 		
		else
			let TOTAL_FILE_CNT++			
			process_file "${1}/${file}" "${INS[*]}" "${OUTS[*]}" #陣列作為一個函式引數傳遞時,必須使用雙引號""
		fi
	done
}

if [ $# -eq 4 ];then
	DIR_NEW=${1}
	DIR_OLD=${2}
	DIR_DIFF_NEW=${3}
	DIR_DIFF_OLD=${4}
elif [ $# -eq 3 ];then
	DIR_NEW=${1}
	DIR_OLD=${2}
	DIR_DIFF_NEW=${3}
elif [ $# -eq 2 ];then
	DIR_NEW=${1}
	DIR_OLD=${2}
else
	echo "param error"
	exit 
fi

#陣列的定義,這裡只是為了使用陣列,才這樣定義的,也可以定義成".c .h .cpp .hpp .mk .sh .mak .ini" 傳遞引數時不用"${INS[*]" 使用"${INS}"
#INS=(.c .h .cpp .hpp .mk .sh .mak .ini)
#INS=(".c" ".h")
#INS=(.c .h)
#OUTS=(".out" ".abs" ".bin")
#OUTS=(.c)

DIR_NEW_LEN=${#DIR_NEW}
DIR_OLD_LEN=${#DIR_OLD}
TOTAL_FILE_CNT=0
DIFF_FILE_CNT=0
START_TIME=$(date +%s)
traverse_directory  "${DIR_NEW}" 
END_TIME=$(date +%s)
ELSPSE_TIME=$(( END_TIME-START_TIME))
echo "ELSPSE_TIME:${ELSPSE_TIME}s,TOTAL_FILE_CNT:${TOTAL_FILE_CNT},DIFF_FILE_CNT:${DIFF_FILE_CNT}"