Resizing Loop Back File Systems

I recently needed to resize an existing loop back file system which was created with dd after some research I came up with the following which worked fine for me.

First you need to get the current image size preferably in megabytes this can be done with

# du -m loop-back-image.img
300 loop-back-image.img

It says the size is 300MB, so here is how we can add another 100MB to it.

# dd if=/dev/zero of=loop-back-image.img bs=1M seek=300 count=100

seek=300 means that dd will start at this point which is the end, and count=100 tells dd to add 100MB to that point, so we end up with a total size of 400MB.

Run resize2fs on the enlarged 400MB image, it will resize the ext2 filesystem on it to fill the image.

# resize2fs loop-back-image.img

If you want to reduce the loop back image size you first have to resize the filesystem on it.

# resize2fs loop-back-image.img 200M

Afterwards you can run dd on the 300MB image to reduce it to 200MB.

# dd if=/dev/zero of=loop-back-image.img bs=1M seek=200 count=0

Again seek=200 says dd to start at 200MB and count=0 means that it should add nothing to that point so we end up with a total image size of 200MB.