Shrink disk partition image
From WickyWiki
Create a copy:
cp org_partition.img new_partition.img
Defragment unused space:
sudo mkdir /mnt/tmp sudo mount new_partition.img /mnt/tmp sudo e4defrag /mnt/tmp sudo umount /mnt/tmp sudo rmdir /mnt/tmp
Create a device for the image, note the returned '/dev/loop20' might be different for you:
sudo losetup -f --show new_partition.img /dev/loop20
Check and fix the file system:
sudo e2fsck -f /dev/loop20
Shrink your file system to the minimum size. Note:
- that this does not shrink the image file itself. That will be done with 'truncate'
- that there will be non-continuous free space preventing the image from being smaller, copying all files (rsync) to a blank system would be the only way to fix this
sudo resize2fs -M /dev/loop20 Resizing the filesystem on /dev/loop20 to 1304194 (4k) blocks. The filesystem on /dev/loop20 is now 1304194 (4k) blocks long.
1304194 * 4 * 1024 bytes = 5341978624 bytes
Disconnect the device:
sudo losetup -d /dev/loop20
Truncate the file:
truncate -s 5341978624 new_partition.img
Enlarge the file system again to fit available space:
resize2fs -f new_partition.img The filesystem is already 1304407 (4k) blocks long. Nothing to do!
Check and allow the tool to fix errors:
e2fsck -f new_partition.img Pass 1: Checking inodes, blocks, and sizes Pass 2: Checking directory structure Pass 3: Checking directory connectivity Pass 4: Checking reference counts Pass 5: Checking group summary information Block bitmap differences: -(531654--531655) -(532478--532479) -(857474--858485) Fix<y>? yes Free blocks count wrong for group #16 (815, counted=819). Fix<y>? yes