16

I'm in the process of experimenting with backing up a Raspberry Pi (Raspbian) sd card. I'm using Win32DiskImager to read the image (from SD card reader) onto my HDD, successfully - but now the size issue. The image is just bigger than the original SD card and can only be written back to a bigger SD card, which, if you back that up has the same problem.

After creating an .img file, how can I remove all the unused space again? (is this because I used raspi-config to allocate all available space to the root?)

I tried to get an idea of what the partition(s) look like with Cygwin, but can't manage to get fdisk working (-bash: fdisk: command not found) - (after reading Image of a 16Gb card containing unpartitioned space at the end: Truncating possible?)

Renier Delport
  • 361
  • 1
  • 4
  • 12

3 Answers3

14

So the best way I have found is to use GParted (you can either use a Linux-based OS, or boot from a GParted Live USB). It is simple enough to find detailed instructions on how to do each of these steps in detail, but here is the general method I have found to work:

  1. Run GParted, find your SD card in the device list and shrink the main partition to as small as it will go.
  2. Take the value of the last sector of this partition and multiply this by the sector size (512 for me; I presume this is standard, although you can check this in GParted settings for your device): this will give you the total size in bytes to copy.
  3. Divide the total number of bytes by 4096 (round up if you need to - better to take a bit more space than not enough), and this will give you the 'count' to then enter into the following command at the terminal in a Linux environment (You can probably do this from the GParted Live USB operating system terminal or in Cygwin without sudo so long as you are running it as an administrator):

sudo dd if=/dev/mmcblk0 of=/path/to/your/file.img bs=4k count=<count>

Change the input device location if you need to. This should give you a final image file that is the smallest that it can be, omitting empty space.

Mike Roberts
  • 625
  • 1
  • 7
  • 13
11

The exists a nice tool called pishrink which reduces the size of a dd image as much as possible by shrinking the root partition. If you start up the restored image the first time the partition is expanded to it's maximum size again. If you run Windows just use your Linux on your Raspberry to shrink the image.

framp
  • 896
  • 7
  • 17
1

Newest version of Win32DiskImager has option Read Only Allocated Partitions. It writes only used space, not empty.

  1. Shrink partition on sd card with GParted.
  2. Create image with Win32DiskImager from bigger card.
  3. Write image with Win32DiskImager on smaller card using option mentionted higher.