Shrinking disk images on Linux

By gill, 17 December, 2023

First enable loopback:

$ sudo modprobe loop

Request a free loopback device:

$ sudo losetup -f

This returns the name of a device, such as /dev/loop0 Now create a device of the image:

$ sudo losetup /dev/loop0 somedisk.img

This sets up /dev/loop0 to represent somedisk.img. Load the partitions into the kernel:

$ sudo partprobe /dev/loop0

Now you can run gparted and do whatever:

$ sudo gparted /dev/loop0

When you don't need the loopback device any more:

$ sudo losetup -d /dev/loop0

Now to resize the image.

Use fdisk to see the block sizes of the partitions in the image:

fdisk -l somedisk.img 
Disk somedisk.img: 59.48 GiB, 63864569856 bytes, 124735488 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x3cedfd53

Device         Boot   Start      End   Sectors  Size Id Type
somedisk.img1          2048   264191    262144  128M  c W95 FAT32 (LBA)
somedisk.img2        264192 54284287  54020096 25.8G 83 Linux
 

Fdisk tells where the end of the partition is (under End). Multiply by 512 to get the new image size.

$ truncate --size=$[(54284287+1)*512] somedisk.img

Now the image size is reduced.

Private
Yes