Shrinking an Image File - aceisace/Raspberry-Pi-Setup GitHub Wiki

This is a copy of the file raspbian-shrink. All credit goes to cotswoldjam (Andrew Oakley)

Shrinking an Image

Often, after fininshing a project on the raspberry, it's very advisable to make a backup of the image (os) in case something does go wrong on the original image. The problem arises actually after that. If you flash a 5GB image on a 32 GB micro SD card and try to make a backup, it's actually going to be 32 GB big. If you often neeed to make a image, the space on your hard disk / ssd will be consumed very quickly.

Another case: You made a backup of a 8GB micro SD card. Then, you try to flash it on another 8GB microSD card. There's a 50/50 chance that the backup will fit on the new micro SD card.

Problem

Even with same microSD cards (capacities) of the the same brand, there are minimal changes in the bytes size:

  • microSD card 1: 1029408
  • microSD card 2: 1029370

The second microSD card is a teeny bit smaller than the 1st one. Normally, the image of card 1 won't fit on the second card. You'd have to get a 16GB card to fit the image, that is unless you can shrink the image file.

Solution

Andrew Oakley knew of this problem and created a user-friendly bash script. It takes care of the shrinking by 'trimming' the image file. Most of it is actually free space anyway, so there's no harm. For example, a 8GB image can be trimmed down to mere 3-4GB by 'shrinking' it. Then, that shrinked image can be flashed even on a 4GB micro SD card. Pretty useful!

Usage

Copy the bash file to a Linux OS and execute sudo chmod +x raspbian-shrink.sh in the folder containing the bash file. Then, move the image to the same folder as the bash file. To use the bash file, use:

sudo bash raspbian-shrink.sh [ -f ] [ -m FREESPACEMB ] imagename.img [ output.img ]

If you need to overwrite the image (just shrink the original), use:

sudo bash raspbian-shrink.sh -f imagefile.img imagefile.img