home_backupコマンド

/homeをバックアップするための簡単なシェルスクリプトを作成してみた。個人的な利用が目的なので汎用性は無視してある。
バックアップ先のパーティションは通常はマウントしていない状態なので、まず、パーティションをマウントする。その際に、色々な確認をしている。
cronで実行しても、気がついたときに実行してもいいだろう。「お手軽ツール」でありあまりインテリジェントはないのでcron等で自動実行するためには、もう少し手を加えた方が良いかもしれない。(例えば、シグナルの処理とか。)

#!/bin/sh

# home_backup v 0.0000000001 (2008/01/02)
# Copyright (C) 2008 Adsaria

# This program is free software; you can redistribute it and/or
# modify it.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY.

CMD=`basename $0`

SRC_DIR=/home/
DST_DIR=/secondary/home/

ROOT_DEV=`df / | tail -1 | awk '{print $1}'`
SRC_DEV=/dev/sda3
DST_DEV=/dev/sdb3

MessageAndLog () {
	echo "$1"
	logger "$1"
}

UNMOUNT=false

MOUNT_DEV=`df $DST_DIR | tail -1 | awk '{print $1}'`
if [ $MOUNT_DEV = $ROOT_DEV ]
then
	MSG="$CMD: mounting $DST_DEV on $DST_DIR"
	UNMOUNT=true
	mount $DST_DEV $DST_DIR
	if [ $? != 0 ]
	then
		MSG="$MSG : Failed to mount, exiting."
		MessageAndLog "$MSG"
		exit -1
	fi
	MSG="$MSG : Success."
	MessageAndLog "$MSG"
elif [ $MOUNT_DEV != $DST_DEV ]
then
	MSG="$CMD: Another device($MOUNT_DEV) is mounting on $DST_DIR. Exiting."
	MessageAndLog "$MSG"
	exit -1
fi

MSG="$CMD: Start backup at `date`"
MessageAndLog "$MSG"

rsync -avx --delete $SRC_DIR $DST_DIR
case $? in
	0  ) MSG="Success" ;;
	1  ) MSG="Syntax or usage error" ;;
	2  ) MSG="Protocol incompatibility" ;;
	3  ) MSG="Errors selecting input/output files, dirs" ;;
	4  ) MSG="Requested action not supported" ;;
	5  ) MSG="Error starting client-server protocol" ;;
	6  ) MSG="Daemon unable to append to log-file" ;;
	10 ) MSG="Error in socket I/O" ;;
	11 ) MSG="Error in file I/O" ;;
	12 ) MSG="Error in rsync protocol data stream" ;;
	13 ) MSG="Errors with program diagnostics" ;;
	14 ) MSG="Error in IPC code" ;;
	20 ) MSG="Received SIGUSR1 or SIGINT" ;;
	21 ) MSG="Some error returned by waitpid()" ;;
	22 ) MSG="Error allocating core memory buffers" ;;
	23 ) MSG="Partial transfer due to error" ;;
	24 ) MSG="Partial transfer due to vanished source files" ;;
	25 ) MSG="The --max-delete limit stopped deletions" ;;
	30 ) MSG="Timeout in data send/receive" ;;
	*  ) MSG="Unknown error"
esac
if [ $MSG = "Success" ]
then
	MSG="$CMD: rsync success"
else
	MSG="$CMD: rsync error: $MSG"
fi
MessageAndLog "$MSG"

MSG="$CMD: Finish backup at `date`"
MessageAndLog "$MSG"

if [ $UNMOUNT = "true" ]
then
	MSG="$CMD: unmounting $DST_DEV from $DST_DIR"
	umount $DST_DIR
	if [ $? != 0 ]
	then
		MSG="$MSG : Failed to unmount, exiting."
		MessageAndLog "$MSG"
		exit -1
	fi
	MSG="$MSG : Success."
	MessageAndLog "$MSG"
fi

exit 0