With PiShrink
You might want to look at github.com/Drewsif/PiShrink — it won't run on bare metal mac, so you'll need some kind of emulation/virtualization environment (e.g. VirtualBox/UTM/multipass etc; verified to work fine under multipass), or an actual linux box.
Once you have created the full image with dd, clone the repo or download the file (it's a single bash script) and run in a linux env:
# shrink in-place (modifies original image)
sudo ./pishrink.sh image.img
# shrink to a new file (leaves original image intact)
sudo ./pishrink.sh image.img image-slim.img
It will take a couple of minutes to shrink the image size.
Most of the shrinking magic is done by resize2fs.
Manually, with ootb tools
It should also be possible to do something like, e.g. (assuming the device you want to backup is not the currently booted disk)
- In a non-emulated linux environment attach the physical sdcard and shrink the partition using
resize2fs, parted or some GUI tool like gparted, partitionmanager, etc.
- Get the End sector of the compacted partition with e.g.
sudo fdisk -l divide by the block size (bs, 512 in this example) and then do the copy with dd if=/dev/sda of=disk.img bs=512 count=<End/512>+<SOME-SAFE-EXTRA-SPACE> (untested so not guaranteed to be correct).
NOTE: Unlike the PiShrink option with this scenario you can save time and space by not having to create a full image with dd, especially when sdcard capacity is high, ie a 128/256GB sdcard with only a few GB of actual data.
With SD Card Copier
SD Card Copier comes preinstalled on desktop versions of raspbian and located under the Accessories menu. It will let you make a live copy of the currently booted sdcard to another USB device, so is probably the most efficient way to clone to a physical sdcard. There are also ways to create an emulated USB device backed by a file image as described in https://superuser.com/questions/1062991/linux-usb-mass-storage-emulation although might be tricky to set up on a rpi.
The downside of this method is that you'll need to have a minimal running xorg with dependencies in order to run the utility.
Also see:
init=/usr/lib/raspi-config/init_resize.shfrom/boot/cmdline.txtso I believe I don’t need to shrink image first. – sunknudsen May 15 '21 at 15:57