Skip to content

Instantly share code, notes, and snippets.

@andygock
Created January 13, 2019 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andygock/7e4993c51ca41b1e4975af084ea49708 to your computer and use it in GitHub Desktop.
Save andygock/7e4993c51ca41b1e4975af084ea49708 to your computer and use it in GitHub Desktop.
Back up and restore Raspbery Pi microsd card
#!/bin/bash
#
# Usage:
# ./pi.sh backup /dev/sdb
# ./pi.sh restore /dev/sdb
#
# Files created and used during backup and restore:
# mbr.img sfdisk.dump partition[12].parted
#
# For raspbian images, use minimum 8GB microsd card
#
# this var not used at the moment, we always compress
use_compression=1
# check if binary exists, if not display message and quit
exists () {
hash $1 2> /dev/null || { echo "Command '$1' not found"; exit 1; }
return 0
}
help () {
echo "Usage: $0 backup /dev/sdx"
echo " $0 restore /dev/sdx"
exit 0
}
# check correct number of args
(( $# == 2 )) || help
# check these binaries exist
for cmd in sfdisk partclone.fat partclone.extfs pigz; do
exists $cmd
done
device=$2
if [ "$1" = "backup" ]; then
echo "Making image of MBR..."
dd bs=512 count=1 if=$device of=mbr.img
sfdisk -d $device > sfdisk.dump # just saving as a human readable partition table
echo ""
partclone.fat -N -c -s "${device}1" | pigz -6 > partition1.parted.gz
partclone.extfs -N -c -s "${device}2" | pigz -6 > partition2.parted.gz
sync
fi
if [ "$1" = "restore" ]; then
echo "Restoring image of MBR..."
dd bs=512 count=1 if=mbr.img of=$device
sync
partprobe
echo "Writing to partitions..."
umount "${device}1" &> /dev/null
umount "${device}2" &> /dev/null
sleep 2
pigz -dc partition1.parted.gz | partclone.fat -N -r -o "${device}1"
pigz -dc partition2.parted.gz | partclone.extfs -N -r -o "${device}2"
sync
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment