I setup a QEMU virtual machine the other day so that I could play with Gentoo Linux, which we were talking about at work on Wednesday. Unfortunately, as I was halfway through the install process untarring the large Portage tree, I realized that I had made the root partition too small. Doh! Faced with the prospect of having to make a new virtual machine and repeat the length install process, I wondered if there was a way to expand the virtual machine image and repartition without losing any data.
Well, it’s possible and here’s how I did it.
First, use the dd
command to expand the image. This is as simple as telling it to write 0 bytes at the point where you want the file to end. I used bs=1
because the seek
parameter takes it value in blocks and setting the block size to 1 was the easiest way to make it do what I want without having to do any arithmetic.
dd bs=1 if=/dev/zero of=gentoo_disk.img seek=2G count=0
Then I checked that it worked with qemu-img info:
marc@ubuntu:~$ qemu-img info gentoo_disk.img
image: gentoo_disk.img
file format: raw
virtual size: 2.0G (2147483648 bytes)
disk size: 1.3G
Then I launched my virtual machine:
qemu -user-net -boot d -cdrom install-x86-universal-2005.1-r1.iso
gentoo_disk.img
Within the virtual machine, I then used fdisk to delete last partition and add it back. And then I resized the ext2 filesystem with:
e2fsck -f /dev/hda3
resize2fs /dev/hda3
This was just beautiful. Another reason to love the flexibility of virtual machines. Essentially that dd command was the analog of saying, “Nah, a 1 GB hard drive is not going to do it for this machine so let me magically make it into a 2 GB drive and leave all my data intact.”
Actually, the parts of this recipe from the fdisk and beyond should be applicable to any Linux environment. It’s quite cool that you can resize a filesystem in Linux – I know of no way to do this in Windows, at least not without some kind of third-party tools. And on the Mac, I really have no idea.
Anyway, this little bit of magic put a smile on my face.