Shrinking Raspberry Pi Images

If you like creating backup images of the SD cards used for your Raspberry Pi projects with ‘dd’ you’ve probably come across the problem that the image file has the same size as the SD card. Storing such large files becomes expensive over time and restoring them to an SD card takes a long time. It would be much better if the image file only had the size of the files while still being restorable to SD cards as before. Recently I’ve come across a project on Github that does just that.

PiShrink is the name of the project on Github by Drew Bonasera. The project mainly consists of a bash shell script and the only parameter given to it is the name of the image file produced by ‘dd’. It then mounts the partitions contained in the image file in /tmp (this takes no space in the tmp drive, it’s just a mount point) and does the following:

  • First it evaluates how much data is on the system partition;
  • Then it shrinks the partition and file system. This will take a while as file system blocks have to be rearranged;
  • It then puts a command in /etc/rc.local to expand the system partition again after the image has been restored back to an SD card;
  • Finally it cuts the part of the image file that is no longer needed.

When the image is restored to an SD card and run for the first time again, the command in /etc/rc.local expands the partition again and the Pi is rebooted once. All of this is done automatically and only takes a couple of seconds.

This way I could shrink a couple of 16 GB images to around 6 GB. Not only does that take much less space on my backup drive but restoring the image to an SD-card is much faster as well!

Hat tip to Christoph Langer for blogging about this a few weeks ago.