Inhaltsverzeichnis

sbMediaBak

A script to backup any removable media eg usb sticks and sd cards.

Features

Installation

1. Create the config file .sbmediabakrc in your home dir with the following content:

#!/bin/bash
# file: $HOME/.sbmediabakrc
 
# Mandatory: The directory to be backuped:
# Please overwrite!
SOURCE="/media/disk"
 
# Optional: An alternative backup target directory:
# The default is $HOME/bak/ + $SOURCE
#TARGET="/somewhere/else"
 
# Optional: Max number of backup archives:
# The default is 4
#MAXBAKS=4

2. Create the backup script '/usr/local/bin/sbmediabak' with the following content and make it runnable:

#!/bin/bash
#
# sbmediabak
# Version 2008-06-12
# By Stefan Beckert
# A backup script for any removable media eg usb sticks and sd cards
# See http://wiki.think-deep.com/becki:sources:sbmediabak
# Public Domain
# No warranty expressed or implied. Use at your own risk.
 
function abort() {
    echo "ERROR: $1!" >&2
    if [ "$2" ]; then errcode=$2 ; else errcode=1 ; fi
    exit $errcode
}
 
MAXBAKS=4
rc="$HOME/.sbmediabakrc"
. "$rc" 2>/dev/null || abort "Can't read $rc! Please create it"
 
# Check if source exists:
[ "$SOURCE" ] || abort "Please specifiy backup source with e.g. \"SOURCE=/dir/of/source\" in \"$rc\""
[ -d "$SOURCE" ] || abort "Source \"$SOURCE\" is not a directory"
SOURCE="$(realpath $SOURCE)"
 
# Set the target:
[ "$TARGET" ] || TARGET="$HOME/bak$SOURCE"
[ -d "$TARGET" ] || abort "TARGET \"$TARGET\" is not a directory. Please create it"
TARGET="$(realpath $TARGET)"
 
# User info:
echo "SOURCE  =  $SOURCE"
echo "TARGET  =  $TARGET"
echo "MAXBAKS = $MAXBAKS"
 
# make archive from last backup rsynced dir:
if [ -r $TARGET/lastrun ]; then
  echo "making archive from last backup of $(cat $TARGET/lastrun)"
  tar -cz -C $TARGET -f $TARGET/$(cat $TARGET/lastrun).tgz newest
fi
 
# copy the data:
rsync -av --delete $SOURCE/ $TARGET/newest
 
# remove oldest backups if there are more than MAXBAKS:
while
  baks=$(ls -1tr $TARGET/*.tgz 2>/dev/null)
  anz=$(echo -e "$baks" | wc -l)
  test $anz -gt $MAXBAKS
do
  oldest=$(echo -e "$baks" | head -n 1)
  echo "removing $oldest"
  rm $oldest
done
 
# remember date of this run for next backup:
date +%Y-%m-%d_%H-%M-%S > $TARGET/lastrun

Configuration

Just specifiy the directory you want to backup in .sbmediabakrc . On a linux system this is often /media/disk. Use the mount command if you are not sure wher your card or stick is mounted.

Usage

  1. Plug your SD-card or USB-Stick
  2. If you don't have automount, then mount your card manually
  3. Type sbmediabak in the command line.