0

Shrink an .img file from the command line

I need to be able to shrink the .img for use on other drives. I can do this using gparted, but do not always have a GUI, so I want to translate the gparted step below into parted

to be verbose, here is my whole proceedure using gparted

insert sd card

$ lsblk

copy image

$ sudo dd bs=4M if=/dev/mmcblk0 of=rp4-ubuntu-server-22.04-fresh.img status=progress oflag=sync

create a loopback device

$ sudo losetup -f
$ sudo losetup /dev/loop0 /home/phil/dl/rp4-ubuntu-server-22.04-fresh.img
$ sudo partprobe /dev/loop0

resize the partition (This is where I need help!)

$ sudo gparted /dev/loop0

resize --> drag to desired size --> apply --> exit gparted

done with the loopback device

$ sudo losetup -d /dev/loop0

find last sector

$ fdisk -l /home/phil/dl/rp4-ubuntu-server-22.04-fresh.img
   Disk /home/phil/dl/rp4-ubuntu-server-22.04-fresh.img: 59.63 GiB, 64021856256 bytes,
125042688 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: 0x1b140081

   Device                                           Boot  Start     End Sectors  Size Id Type
   /home/phil/dl/rp4-ubuntu-server-22.04-fresh.img1 *      2048  526335  524288  256M
c W95 FAT32
   /home/phil/dl/rp4-ubuntu-server-22.04-fresh.img2      526336 7739391 7213056  3.4G 83 Linux

resize the .img

$ sudo truncate --size=$[(7739391+1)*512] /home/phil/dl/rp4-ubuntu-server-22.04-fresh.img

Can you show me how to accomplish the gparted step using cli parted?

Paul
  • 3,037
  • 6
  • 27
  • 40
posop
  • 247
  • 2
  • 10

1 Answers1

0

Yes. Here is the way I am doing it.

Assuming the data presented in your post, this should do the trick: Entering the parted app to resize the desired partiton:

parted /dev/loop0

checking for the current state:

print

Assuming you want the second partition for resizing - and that you want the second partition to "end" on the "7739391" sector, you can resize the desired partition with "resizepart" (inside the "parted" CLI):

resizepart 2 7739391s

You can check again with print. If everything is ok, save it and exit parted with

quit

The usual warning - please backup any important data before doing stuff like this, yada, yada, yada :) ... Have a nice day