开发 / 测试环境
- 树莓派:
Raspberry Pi 3b
- TF 存储卡:
SanDisk Ultra 16GB Class 10 A1
- 操作系统:
2018-06-27-raspbian-stretch-lite
- 程序:使用
apt-get
安装的最新版本(2018年7月15日)
脚本
脚本raspberrypi-backup.sh
用于生成树莓派的最小系统镜像。
该脚本能够将位于 TF 存储卡上的数据备份到通过USB连接的存储设备上。镜像的大小取决于 TF 存储卡的已用空间。
脚本接受1个必要参数:存放镜像的目录。每次执行,脚本会在该目录中生成一个img
文件,文件名为backup_当前日期与时间.img
。
#!/bin/bash
set -e
# start
if [ -z $1 ]; then
echo "Backup directory not set, required."
exit 1
fi
BACK_UP_DIR=$1
echo
# install
echo "Installing package ..."
apt-get install dosfstools dump parted kpartx -y
echo "Finish."
echo
# create image
echo "Creating image ..."
ROOT=`df -P | grep /dev/root | awk '{print $3}'`
MMCBLK0P1=`df -P | grep /dev/mmcblk0p1 | awk '{print $2}'`
ALL=`echo $ROOT $MMCBLK0P1 |awk '{print int(($1+$2)*1.2)}'`
TIME=`date "+%Y%m%d%H%M%S"`
FILE=$BACK_UP_DIR/backup_$TIME.img
dd if=/dev/zero of=$FILE bs=1K count=$ALL
echo "Finish."
echo
# part
echo "Parting image ..."
P1_START=`fdisk -l /dev/mmcblk0 | grep /dev/mmcblk0p1 | awk '{print $2}'`
P1_END=`fdisk -l /dev/mmcblk0 | grep /dev/mmcblk0p1 | awk '{print $3}'`
P2_START=`fdisk -l /dev/mmcblk0 | grep /dev/mmcblk0p2 | awk '{print $2}'`
parted $FILE --script -- mklabel msdos
parted $FILE --script -- mkpart primary fat32 ${P1_START}s ${P1_END}s
parted $FILE --script -- mkpart primary ext4 ${P2_START}s -1
parted $FILE --script -- quit
echo "Finish."
echo
# mount
echo "Mounting ..."
LOOP_DEVICE=`losetup -f --show $FILE`
kpartx -va $LOOP_DEVICE
PART_BOOT="/dev/dm-0"
PART_ROOT="/dev/dm-1"
echo "Finish."
echo
# format
echo "Formating ..."
mkfs.vfat $PART_BOOT
mkfs.ext4 $PART_ROOT
echo "Finish."
echo
# backup prepare
MOUNT_POINT=/media/backup_$TIME/
if [ ! -d "$MOUNT_POINT" ];then
mkdir $MOUNT_POINT
fi
# backup /dev/boot
echo "Backing up disk /dev/boot ..."
mount -t vfat $PART_BOOT $MOUNT_POINT
cp -rfp /boot/* $MOUNT_POINT
umount $MOUNT_POINT
echo "Finish."
echo
# backup /dev/root
echo "Backing up disk /dev/root ..."
mount -t ext4 $PART_ROOT $MOUNT_POINT
cd $MOUNT_POINT
dump -h 0 -0uaf - / | sudo restore -rf -
cd
umount $MOUNT_POINT
echo "Finish."
echo
# unmount
echo "Unmounting ..."
kpartx -vd $LOOP_DEVICE
losetup -d $LOOP_DEVICE
rm -fr $MOUNT_POINT
echo "Finish."
echo
# end
echo "Back-up image $FILE is successfully created."
echo