Skip to content

Instantly share code, notes, and snippets.

@selimnairb
Last active December 10, 2021 12:54
Show Gist options
  • Save selimnairb/ba819d936d0d3c9ab9d5a46adf887842 to your computer and use it in GitHub Desktop.
Save selimnairb/ba819d936d0d3c9ab9d5a46adf887842 to your computer and use it in GitHub Desktop.
Make a custom shrunken Raspbian image

Quickly and efficiently create a custom shrunken SD-card image for Raspberry Pi computers

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.

1. Resize the SD card

  • 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.

2. Record the last sector of the newly resized partition

  • 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.

3. Create an image of the resized SD card

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.

4. Burn the image to another SD card

For subsequent duplication we will also use dd:

dd bs=1M if=MY_IMAGE_NAME.img of=/dev/sdc conv=sync

5. Expand the filesystem after first boot

Use raspi-config to expand the root filesystem on first boot:

  • sudo raspi-config
  • Choose Advanced Options
  • Choose Expand Filesystem
  • Reboot

That's it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment