How to format a disk image

Usually, you won’t create a disk image; in fact most of the times you would download it and then mount it somewhere or burn it to a CD/DVD.
However, there are cases in which you could need to create a disk image of a given size, format it and then mount it as a normal device. This happens for example when you want/need to set up a swap file instead of a swap partition or if you want to get a fake floppy disk drive when you don’t even have the driver.

So, let’s see how can you create, format and mount a floppy disk1 fake image:

  1. Create the file that will contain the image with

    $ dd if=/dev/zero of=/full/path/image.iso bs=1k count=1440

    In this case the image will be created in /full/path with the name image.iso and with the size of 1.44MB;

  2. Associate a loop device for it:
    # losetup /dev/loop0 /full/path/image.iso

    This makes /dev/loop0 pointing to the our new file. This allows us to call fdisk, mkfs and any other tool we tipically use for devices.

  3. Create a single main partition:
    # fdisk /dev/loop0

    Then press n, 1, enter, enter and w

  4. Format it:
    # mkfs /dev/loop0

    If you had wanted to make a swap file you would have used mkswap in the place of mkfs.

    1. but can be used for other cases too

    None
    A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".