Backup and restore Raspberry Pi’s OS

Usually, Raspberry Pi computer users install their OS on a microSD card. The capacity and speed of the microSD card have increased rapidly in recent years, but the price has decreased. For example, an A2 class 512GB microSD card is only ¥449, while a Raspberry Pi 4B computer with 8GB memory is ¥719 (in 2023-09). Many users (maybe just me ^_^) choose a large-capacity card to install OS on. In the early years, I used the dd command to backup and restore Raspberry Pi’s OS. However, it is a waste of storage devices to do that. Here is a guide to back up and restore OS using the tar command and relative tools.

Supposedly the OS is Ubuntu 23.04 installed by Raspberry Pi Imager. And we will use this OS for backup and restoring. Firstly we back up the OS:

sudo tar czvfp RaspberryPiOS.tar.gz \
  --exclude=/proc --exclude=/sys \
  --exclude=/tmp --exclude=/mnt \
  --exclude=/media --exclude=/lost+found
  --exclude=/run --exclude=/swapfile / 

Then we insert a blank microSD card and make new partitions on it, the device path should be like /dev/mmcblk1.

sudo parted -s  /dev/mmcblk1 -- \
  rm 1 \
  mklabel msdos \
  mkpart primary fat32 1024KiB 500MB \
  mkpart primary ext4 500MB -1s \
  set 1 boot on
sudo mkfs.vfat /dev/mmcblk1p1
sudo mkfs.ext4 /dev/mmcblk1p2

sudo mkdir -p /media/restore/boot/firmware
sudo mount /dev/mmcblk1p2 /media/restore
sudo mount /dev/mmcblk1p1 \ 
  /media/restore/boot/firmware

Finally, we restore the OS on the new microSD card.

sudo tar xzvpf RaspberryPiOS.tar.gz \
  -C /media/restore
cd /media/restore
sudo mkdir -p sys media mnt proc tmp run
sudo chmod 777 tmp
sudo fallocate -l 1024MiB swapfile
sudo sed -i -e 's/LABEL=writable/PARTUUID={mmcblkp2_partuuid}/' etc/fstab
sudo sed -i -e 's/LABEL=system-boot/PARTUUID={mmcblkp1_partuuid}/' etc/fstab
sudo sed -i -e 's/LABEL=writable/PARTUUID={mmcblkp2_partuuid}'
  \ boot/firmware/cmdline.txt

To obtain the PARTUUID of the partitions on the microSD card, execute the following command.

ls /dev/disk/by-partuuid

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注