Awk|Bash – copy the file with preserving the previous version.
Home page Ubuntu C++ Hardware HTML i javascript Java Software SQL

Awk|Bash – copy the file with preserving the previous version.

Added: 2012-03-23

Copy files from a source to a destination with the behavior of the copy of the file with the same name in place of the copy, is very important when you want to have history of changes.

Script in bash named cps (copy secure) has two parameters. First parameter, this is path to file, that is to be copied. Second parameter, this is path to directory destination. If exist file on the same name in destination, and had different control sum, will be created backup that file and next copied file from source.

Script below.

drukowanie kodu zaznaczanie kodu

#!/bin/bash

#echo Script make copy file to destination, if elements exists in folder
#echo do backup file [namefile].[dateTime]

if [ "$2" = "" ]; then
	echo "Prarametr secondary not exists!!!"
	exit 10;
fi

if [ ! -f $1 ]; then
	echo "File '"$1"' not found!!!";
	exit 1;
fi

if [ ! -d $2 ]; then
	echo "Folder '"$2"' not found!!!";
	exit 1;
fi

dt=$2"/"`basename $1`
if [ -f $dt ]; then
	#echo "File "`basename $1`" exists in destination."

	md5File1=`md5sum $1 | awk 'BEGIN{}{print $1}'`;
	md5File2=`md5sum $dt | awk 'BEGIN{}{print $1}'`;
	if [ $md5File1 == $md5File2 ]; then
		echo "File '"`basename $1`"' in destination are the same md5sum.";
		exit 0;
	else
		echo "Making backup '"$dt"'...";
		cp $dt $dt.`date +%y%m%d`_`date +%H%M%S`
	fi
fi

echo "Start coping file '"`basename $1`"'...";
cp $1 $2