The following assumes you have an SD card with Raspbian Stretch Lite on it, and that all commands are run on a separate (from your Raspberry Pi) Linux machine (or VM).
Some of this was adapted from here.
- Put your SD card in an SD card reader
- Run gparted:
sudo gparted
- Select the SD card (
/dev/sdc
in my case) from the device drop-down menu in the upper right - Right click on the ext4 partition (it should be labeled rootfs)
- From the pop-up menu, select Resize/Move
- In the dialog box that appears, select a new size for the partition. Make sure to leave some free space (to be sure that the shrunken Raspberry Pi can successfully boot). For example, my custom Raspbian install used 1.28 GiB, so to be safe, I resized my partition down to 2048 MiB (I was using an 8GB SD card).
- Click Resize/Move to close the dialog box
- From the tool bar, click on the "Apply All Operations" button, which looks like a check mark.
Gparted will then resize your partition. You can check the status for errors. The only error I came across was because I tried to make my partition too small.
Keep gparted open as we will need it for the next step.
- Right click on the newly resized partition, and select Information from the pop-up menu.
- Take note of the Last sector of the partition (4292607 in my case).
- Close gparted.
All we need to do is read data from the SD card up through the end of the resized rootfs partition. We will use dd
for this:
dd if=/dev/sdc of=MY_IMAGE_NAME.img bs=512 count=4292608
Note that this assumes your SD card uses 512 bytes/sector (it might be 1024 bytes/sector). If you are unsure, do the following:
fdisk -l -u=sectors /dev/sdc
Note also, for the
count
parameter, we use the "number of the last sector, plus 1", so 4292608 rather than 4292607. You may be able to get away without adding one, but I wanted to avoid a fence-post error, and this seemed to work.
For subsequent duplication we will also use dd
:
dd bs=1M if=MY_IMAGE_NAME.img of=/dev/sdc conv=sync
Use raspi-config to expand the root filesystem on first boot:
sudo raspi-config
- Choose Advanced Options
- Choose Expand Filesystem
- Reboot
That's it.