Zero Free Space on Linux Ubuntu under Hyper-V

Linux is hard. Stuff that is simple in Windows takes forever to figure out. In this case, I wanted to archive a Hyper-V virtual machine (export it and zip it up) that is running Ubuntu 18.04 LTS server.

Compression is much more efficient if you can write zeros to the unused portion of the disk before exporting and compressing.

In Windows, that’s easy with Sysinternals SDelete, which runs on the active partition to write zeros to free space.

For Ubuntu Linux, there are of course lots of threads about how to do this (example), how long it takes, whether it’s considered a secure wipe (which doesn’t matter in this situation), etc. I finally found zerofree, which looks like it should to the same thing as SDelete.

But:  zerofree won’t write to a partition in read-write mode, the instructions on the man page didn’t work for mounting as read-only, and I was unable to get into the grub menu under Hyper-V to start in recovery mode. In the end, I downloaded an Ubuntu 18.04.5 LTS server install ISO and booted the Hyper-V virtual machine from that.

Important Do NOT follow the server install wizard—it will overwrite your hard drive. Instead, before the disk configuration step, press Ctrl + Alt + F2 to get a different terminal (see this post). Then you will be ready to run zerofree. Here is what worked for me. Use at your own risk!

sudo –s [become root—no password required when booted from ISO]
fdisk -l [to list disks]
mkdir /mnt/mydrive
mount -o ro /dev/sda1 /mnt/mydrive [mount read-only]
df [to see that drive is mounted, with free space]
ls /mnt/mydrive [to see if drive is readable]
zerofree -n -v /dev/sda1 [dry run]
zerofree -v /dev/sda1 [only takes a few minutes]
shutdown -h now

As the machine shuts down, you’ll be prompted to remove the installation media and press Enter. Check the machine’s Hyper-V settings to make sure the ISO is no longer mounted as a virtual DVD, finish shutdown, then start the machine.  Poke around to make sure it’s still working, shut it down, export from Hyper-V, and compress.

In my test, my 30GB drive compressed to about 21GB without using zerofree. After zerofree, it compressed to under 7GB.

1 thought on “Zero Free Space on Linux Ubuntu under Hyper-V

  1. angeloxo

    You can use this:

    dd if=/dev/zero of=wipefile bs=1M
    sync
    rm wipefile

    Easy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.