8

I have a puppy linux img that is 8gb but I need it to fit on a 6gb drive. How do I resize the ext2 partition on the img?

2 Answers2

9

NOTE Make a backup, anything can go wrong ... I ran all those as root :

  1. bind a loop device to the image: losetup /dev/loop10 $image_file
  2. refresh partitions: partprobe /dev/loop10
  3. adjust partition size: gparted /dev/loop10
  4. undo the loop: losetup -d /dev/loop10
  5. remove unwanted space: truncate -s -${SIZE}G $image_file (you might want to calculate the exact size based on values from fdisk/cfdisk * sector size)

NOTE You might need to double check the partitions' UUIDs, mine seem to have changed and I had to update fstab

abo
  • 91
  • 1
  • 4
  • Isn't the truncate command eg. like this: truncate -s 6GB /yourimagefile.img or truncate -s 6442450944 /yourimagefile.img? But even though I took the end sector and multiplied by the sector size it must somehow have been wrong, because afterwards parted told me "Can't have partition outside the disk" and the image doesn't work... – TheStoryCoder Jul 22 '19 at 10:24
  • Also, the resizepart command in parted was very quick (I used parted instead of gparted). Does it just cut of the partition at the given size? What if files are "physically" located outside the partition boundary - will they just be discarded? – TheStoryCoder Jul 22 '19 at 10:27
  • for fdisk, taking into account only the end sector is not exact. The right calculation is: ( start_sector + partition_sector_count) * sector_size. You use this amount A (in bytes) for truncate: truncate --size={A} $image_file – sugarman Jul 09 '20 at 19:22
  • This answer works great, but the truncate line kept throwing an error. So I added the approximate sizes of the partitions plus a 10M safety margin (eg. truncate -s 250M my.img) and that worked great and left a little unallocated space at the end of the last partition. – Ken H May 04 '23 at 20:07
3

You'll want to shrink the filesystem - any kind of logical volume management or similar containers - then the image. I'm going to assume you're talking about a RAW disk image.

Steps at a glance:

  • Ensure the image is not being accessed (ex: lsof)
  • Shrink the filesystem (ex: resize2fs)
  • Perform a filesystem check (ex: fsck)
  • Shrink any LVM or other kind of containers (if needed)
  • Shrink the disk image (ex: dd to a new image with skip or use qemu-img)
  • Fsck again, test that it works!

Alternative:

  • Create a new image and copy the data / MBR / etc. over.
  • Clone the image with something like partclone

Similar questions:

Reference:

  • no need to assume as they stated "img file" not image file, but despite that, i am not able to follow your steps, can you elaborate on how to make my 2TB .img file to 1TB ? – oemb1905 Oct 31 '21 at 00:19