一个简单的改名备份脚本

Wayne posted @ Wed, 23 Feb 2011 20:27:12 +0000 in Experience , 2685 readers

虽然说打算在服务器上用版本控制来管理部署的程序了,但一时终归还没用起来。而按照惯例,上传新版时旧版是不删的,仅仅改个名字存放起来而已。改名字时也没啥严格规定,一直以来有点乱。当然也许别人重命名还是比较规矩的,但反正我是很随心所欲的,搞得经常自己也记不清楚,只能靠修改时间来辨认。上次写了个脚本,把给名字自动加上时间后缀作为备份命令,倒也还管用。这次想再改进一下,上点参数,能整成 "*.latest", "*.current",  "*.last" 之类的效果。

#!/bin/bash

case "$1" in 
	"") echo "Usage: bak [option] filename"
	    echo "bak: rename a file as a backup"
	    echo "Try \"bak -h\" for help"
	    exit
            ;;
	*)
	   rename=0
	   option=0
	   while getopts "hrlc" flag
   	   do 
		option=1
		case "$flag" in
			"h") helplist=1;;
			"r") let "rename += 1";;
			"l") last=1;;
			"c") current=1;;
		esac
				
	   done
	   if [ "$option" -ne 1 ]
		then
		  filename=$1
		  newfilename=$filename.`date +%Y%m%d%H%M`
		  mv -f $filename $newfilename
		  echo $newfilename
		  exit
	   fi
		;;
esac

if [ "$helplist" = 1 ]; then
	echo "bak: rename a file as a backup"
	echo "Usage: bak [option] filename"
	echo "default(no option): rename filename to filename.`date +%Y%m%d%H%M`"
	echo "Options:"
	echo "	-l:	rename filename to filename.last"
	echo "	-c:	rename filename to filename.current"
	echo "	-r:	cut the end of filename from the last dot, example:"
	echo "			filename.last  --> filename"
	echo "multiple r will try to cut multiple part split by dot from the end, as:"
	echo "		-rrr	filename.section1.secion2.section3 --> filename"
	exit
fi
	
case "$2" in
	"") echo "Usage: bak [option] filename"
	    echo "bak: rename a file as a backup"
	    echo "Try \"bak -h\" for help"
	    ;;
	*)
	   filename=$2	
	   newfilename=$filename
	   if [ "$rename" -ne 0 ]; then
		for i in `seq 1 $rename`
  		  do
			newfilename=${newfilename%.*}
		  done
	   fi
	   if [ "$last" = 1 ]; then
		newfilename=$newfilename.last
	   elif [ "$current" = 1 ];then
		newfilename=$newfilename.current
	   else
		newfilename=$newfilename.`date +%Y%m%d%H%M`
	   fi
	   mv $filename $newfilename
	   echo $newfilename
	   ;;
esac 

 


Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter