2008-04-28

simple backup script

This script provides quick-n-dirty timestamped backups while preserving file extensions.

It echos to the console it's operations.

May be used on files or directories.

EXAMPLE
$ bk maxentropy.c
`maxentropy.c' -> `.backup/maxentropy~20080428d22h51.c'

It automatically creates the '.backup' directory and timestamps the filename and copies it there (minute granularity).

Here is the script.

$ cat `which bk`
#!/bin/bash

TARGETDIR=".backup"
SEP="~"
STAMP=`date +%Y%m%dd%Hh%M`

mkdir -p "${TARGETDIR}"
for f in "$@" ; do
  #cp -av "$f" backup/"$f"-`date +%Y%m%dd%Hh%M`

  # using 
  #     DIR="${FULLNAME%/*}"
  #     FILE="${FULLNAME##*/}"
  #     MAXBASE="${FILE%.*}"
  #     MINBASE="${FILE%%.*}"
  #     MAXSUF="${FILE#*.}"
  #     MINSUF="${FILE##*.}"
  #     echo $DIR $FILE $MAXBASE $MINBASE $MAXSUF $MINSUF
  #     /dir base.suf1.suf2 base.suf1 base suf1.suf2 suf2

  f="${f%/}"           #; echo f:$f;
  DIR="${f%/*}"        #; echo DI:$DIR;
  FILE="${f##*/}"      #; echo FI:$FILE;
  MAXBASE="${FILE%.*}" #; echo MB:$MAXBASE;

  # if the file has no extension
  if [ "$FILE" = "${FILE/*./}" ] ;
    then MINSUF="" ;  # filename in MAXBASE already
    else MINSUF="${FILE/*./.}";
  fi ;
  MINSUF="${FILE/*./.}";
  #echo SUF: $MINSUF;
  
  # file name starts with a ".", has no other "." in it
  if [ "$FILE" = "$MINSUF" ] ;
    then
      MAXBASE="${MINSUF}"
      MINSUF=""
  fi
  
  TARGET="${TARGETDIR}/${MAXBASE}${SEP}${STAMP}${MINSUF}"
  #echo $TARGET
  
  # maybe should add "-n" option to show what'll happen
  cp -av "$f" "$TARGET"
done


No comments: