I have a copy of my RPi's SD card made with dd if=/dev/mmblk0 of=backup.img
. This creates a 32GB file. Only about 6GB of it is actually used, the rest is just data from deleted files. How would I remove the old, useless data? It doesn't have to shrink the image file, just zero out whatever isn't needed
1 Answer
I have been successfully using a script called pishrink by Drew Bonasera ('Drewsif') to back up a headless Raspberry Pi 4 (it works for all models). It is useful because after using dd to make the image it optionally shrinks the image with resize2fs to a little above the data size, and also can optionally insert a run-once command into the image to make Raspbian expand the file system when the image is flashed to a card and used for the first time to boot a Pi. I have been making 8 GB images from a 32 GB card.
This means you could flash a smaller card than the original, provided the shrunk image size is smaller than the new card.
https://github.com/Drewsif/PiShrink
It is nice to compress the image to a zip archive (Balena Etcher can use these) but... it is painfully slow if you let the Pi hardware do the compression. As the finished image ends up in a Windows shared folder mounted on the Pi, after PiShrink has finished my script uses sshpass on the Pi to command Windows (OpenSSH enabled) to run pigz (a fast command line parallel Zip tool) and can get the zip archive down to around 5.5 to 6 GB. Or you could use other methods (WinRar, Winzip, 7-zip etc).
fstrim
on the loop-mounted filesystem, just like you would on an SSD. (This will actually make the image file sparse.)"