Skip to content

Instantly share code, notes, and snippets.

@StaticRocket
Last active October 13, 2023 00:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save StaticRocket/8934f78b3da7838ca265aa0223e62608 to your computer and use it in GitHub Desktop.
Save StaticRocket/8934f78b3da7838ca265aa0223e62608 to your computer and use it in GitHub Desktop.
Quickly backup and deploy bootable SD cards with variable size ext4 root partitions
#!/bin/sh
[ -z "$PART_PREFIX" ] && PART_PREFIX=''
DD_ARGS='status=progress conv=fsync'
backup() {
src="$1"
dst="$2"
sfdisk -d "${src}" > "${dst}-table.txt"
sed -i "$ s/size=[ 0-9]*/size=+/" "${dst}-table.txt"
e2image -ra -p "${src}${PART_PREFIX}2" "${dst}-2.img"
e2fsck -fp "${dst}-2.img"
# catch return codes that mean things were repaired
case $? in
0) ;;
1) ;;
2) ;;
*) return 1;;
esac
resize2fs -M -p "${dst}-2.img"
dd if="${src}${PART_PREFIX}1" of="${dst}-1.img" ${DD_ARGS} bs=4K
}
deploy() {
src="$1"
dst="$2"
sfdisk "${dst}" < "${src}-table.txt"
e2image -ra -p "${src}-2.img" "${dst}${PART_PREFIX}2"
e2fsck -f "${dst}${PART_PREFIX}2"
resize2fs -p "${dst}${PART_PREFIX}2"
dd if="${src}-1.img" of="${dst}${PART_PREFIX}1" ${DD_ARGS} bs=4K
}
disk_image() {
src="$1"
dst="$2"
start_sector_list=$(
grep -o -P "(?<=start=)\s*\d+" "${src}-table.txt" | tr -d ' '
)
first_sector=$(echo "${start_sector_list}" | head -1)
last_sector=$(echo "${start_sector_list}" | tail -1)
echo "Using ${first_sector} - ${last_sector} as the starting image..."
dd if=/dev/zero of="${dst}.img" count="${last_sector}"
partition_index=1
for start_sector in ${start_sector_list}; do
echo "Copying partition ${partition_index} ..."
dd if="${src}-${partition_index}.img" of="${dst}.img" \
seek="${start_sector}" ${DD_ARGS}
partition_index=$((partition_index+1))
done
sfdisk -w never -f "${dst}.img" < "${src}-table.txt"
}
help="
[backup/deploy/disk_image] [src] [dst]
Example: backup /dev/sdc working-image
"
if [ $# -eq 3 ]; then
case $1 in
"backup")
backup "$2" "$3";;
"deploy")
deploy "$2" "$3";;
"disk_image")
disk_image "$2" "$3";;
*)
echo "$help"
esac
else
echo "$help"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment