I have a script that I run in order to optimize the disk space prior to backing up a virtual guest (really doesn't matter too much which hypervisor is used).
Modern Ubuntu versions (e.g. 18.04) seem to default to using a /swapfile
rather than a partition for the purpose. That's fine, too.
However, I'd like to zerofill the swap file along with the root partition containing it.
With swap partitions this was relatively painless as there was always a way to extract the existing $UUID
from the swap partition and – after zerofilling the partition – run mkswap -U $UUID
to re-create said swap partition.
However, with the /swapfile
I don't see how to do that. While I realize that you can't mount a /swapfile
by UUID in /etc/fstab
, I'd still want to retain the UUID.
So I reckon need one of the following to proceed:
- I need a method that can zerofill the swap file without also wiping those structures that make it a swap partition (i.e. avoid having to run
mkswap -U $UUID
) - I need a method to retrieve the existing UUID from a swap file (as opposed to a partition where I can use anything from
blkid
to looking at/dev/disk/by-uuid/$UUID
…)
Best Answer
This won’t clear the swap file as thoroughly as re-creating it, but if you clear it after skipping the first 4KiB (strictly speaking, the first page, which depends on your architecture), you won’t touch any of the structures which identify a swap file.
blkid
works fine on swap files too:The header format is defined in the kernel: the old format has a magic value at the end of the first page, the new format combines that with a 1KiB free area, then a number of fields (version, size, bad pages, UUID, label) which all fit comfortably inside the first page.