Resizing a virtual hard drive

ddfilesystemsmkfs

I found a very nice tutorial on how to create virtual hard disks, and I am considering using these for my work in order to store reliably and portably large datasets with associated processing results.

Basically, the tutorial consist in doing this:

dd if=/dev/zero of=MyDrive.vhd bs=1M count=500
mkfs -t ext3 MyDrive.vhd
mount -t auto -o loop MyDrive.vhd /some/user/folder

which creates a virtual hard drive of 500MB formatted in ext3 and mounts it somewhere.

Now say I use that file and realise I need more than 500MB, is there a way of "dynamically" resizing the virtual disk? (By dynamically I mean other than creating a new bigger disk and copy the data over.)

Best Answer

There is better alternative than dd to extend a file. The dd command requires several parameters to run properly (to not corrupt your data). I use truncate instead. Despite of its name it can extend the size of a file as well:

truncate - shrink or extend the size of a file to the specified size

-s, --size=SIZE

set or adjust the file size by SIZE

SIZE is an integer and optional unit (example: 10M is 10*1024*1024). Units > are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB, ... (powers of 1000).

SIZE may also be prefixed by one of the following modifying characters: '+' extend by, '-' reduce by, '<' at most, '>' at least, '/' round down to multiple of, '%' round up to multiple of.

thus,

truncate -s +1G MyDrive.vhd

safely expands your file by 1 gigabyte. And, yes, it does sparse expansion when supported by the underlying filesystem, so the actual blocks would be allocated on demand.

When a file is expanded, don't forget to run resize2fs:

resize2fs MyDrive.vhd

Also, the whole thing may be done online (without umount'ing the device) for file systems that support online resize:

losetup -c loopdev

updates in-kernel information on a backing file,

and

 resize2fs loopdev

resizes the mounted file system online

Related Question