Backup and Restore SD Cards using linux

Once a Pi is setup, it’s useful to clone the SD card and save the state. Here’s how.

# install shrink it
wget https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh
chmod +x pishrink.sh
sudo mv pishrink.sh /usr/local/bin

# insert sd, copy whole (incl. partitions) to a file. 
# Will be the SIZE OF THE WHOLE SD CARD: we'll fix this later
sudo dd bs=4M if=/dev/mmcblk0 of=rpi.img conv=fsync 
# shrink it
pishrink -p rpi.img 

# write it: insert a fresh card
umount /dev/mmcblk0p1 /dev/mmcblk0p2 # if automounted
dd bs=4M if=rpi.img of=/dev/mmcblk0 status=process conv=fsync 

# some useful commands
sudo fdisk -l /dev/mmcblk0   # 'physical' disk details
file original.img            # img file partitions
losetup                      # mount a .img file (see note below)
fsck                         # check the filesystem/s

See more details on losetup too.

But wait! Is it exactly the same on a different machine? No! Change the cloned Pi a bit:

  • Hostname (raspi-config and reboot)
  • AP and MAC address-related (e.g. ap0 interface),
# get mac addr of wlan0 interface and change from masterpi's mac
iw dev 
sudo vi /etc/udev/rules.d/70-persistent-net.rules
# change AP name
sudo vim /etc/hostapd/hostapd.conf 

Leave a Reply

Your email address will not be published. Required fields are marked *