Making a Reduced Size Pi IMG for backups

Here is a technique for creating an image of an SD card (or any other filesystem) and then reducing the size of that image to exclude unallocated space in the image file system. If you are doing this on a Raspberry Pi you will need to ensure your SD card is large enough to hold both the original and the shrunk image. Alternatively, you could connect an external storage device to hold the images.

Simple Image Creation

Start by creating an image of the SD card with the following command:

sudo dd if=/dev/sdc of=./myImage.img

Where /dev/sdc is the location of the SD card you want to image and ./myImage.img is the desired name and location of the image file.

Better Image Creation

A more sophisticated version of dd can be found by installing dc3dd:

sudo apt-get install -y dc3dd

In addition to creating an image file, dc3dd also provides a progress report and confirmation that the job was completed successfully.

To create an image with dc3dd tool enter:

sudo dc3dd if=/dev/sdc of=./myImage.img


Establish the used space and truncate the image

Next you need to know the position of the last allocated sector in the image. To find that type:

fdisk -l myImage.img

The two important details you need from the output are: Units (normally 512 bytes) and the last used sector.

To eliminate the unallocated space from the image use the truncate command as follows:

sudo truncate –size=$[(8447999+1)*512] myImage.img

NB: There are two dashes immediately prior to size in the above – some browsers show this as a single long dash – grrr!

Where 8447999 is the final sector on your image, 512 is the block-size and myImage.img is the  name of the image file you want to shrink. The bracketed section simply adds 1 to the number of blocks in the wanted section and multiplies the total by 512 to calculate the size of the wanted section in bytes. All data above that value is truncated.

That’s it!

What if there’s no unallocated space on the SD Card?

If you have expanded the filesystem on the SD Card but not all the space is in use, you first need to create unallocated space that can be removed later with the truncate command.

To do this, run gparted to view the SD Card’s file system and use the Partition menu to resize the target partition and convert the unused space into unallocated space. Once complete, you can use the truncate command as above to remove it.

Mike – G4WNC


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s