Create blank disk image for file storage

Similar to the way Mac OS X users can create and mount blank .dmg files, add and remove files as much as they wish, and move that image wherever they want... as if it were a virtual USB drive.

Is there an equivalent for Ubuntu? I know that the "Disk Image Mounter" allows us to mount and edit existing .img files, but is there an equally easy way to create/format empty .img files? Every solution I have found so far implements copying/cloning an already existing drive, but I don't want that.

EDIT: I created a scripted GUI application based on the answer accepted below. It's just a dialog based on YAD and .sh files, it's meant to make the dd command/mount/format process easier to handle for not-so-command-line-savvy people.

Here it is


Yes.

This is a step-by-step guide to create a custom image starting from scratch;

I'll assume the following:

  • The image size should be 100 MiB
  • The image partition table should be MBR
  • The image should contain a single FAT32 primary partition

Creating the blank image

Create the blank image:

dd if=/dev/zero of=image.img iflag=fullblock bs=1M count=100 && sync
ubuntu@ubuntu ~/tmp % dd if=/dev/zero of=image.img iflag=fullblock bs=1M count=100 && sync
100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 0.0415825 s, 2.5 GB/s
ubuntu@ubuntu ~/tmp % tree
.
└── image.img

0 directories, 1 file

Mounting the blank image

List the already busy loopback devices:

losetup
ubuntu@ubuntu ~/tmp % losetup                   
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0         0      0         0  1 /cdrom/casper/filesystem.squashfs

Mount the image on the first available loopback device:

sudo losetup loop1 image.img
ubuntu@ubuntu ~/tmp % sudo losetup loop1 image.img
ubuntu@ubuntu ~/tmp % losetup
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0         0      0         0  1 /cdrom/casper/filesystem.squashfs
/dev/loop1         0      0         0  0 /home/ubuntu/tmp/image.img

Partitioning / formatting the blank image

Run gparted passing the loopback device as an argument:

sudo -H gparted /dev/loop1

screenshot1

Click on "Device" -> "Create Partition Table...":

screenshot2

Click "Apply":

screenshot3

Click on "Partition" -> "New":

screenshot4

Select "fat32" from the drop-down menu:

screenshot5

Click "Add":

screenshot6

Click the green tick:

screenshot7

Click "Apply":

screenshot8

Click "Close":

screenshot9

And close Gparted.

Unmounting the image

Finally, unmount the image from the loopback device:

sudo losetup -d /dev/loop1
ubuntu@ubuntu ~/tmp % sudo losetup -d /dev/loop1
ubuntu@ubuntu ~/tmp % losetup
NAME       SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE
/dev/loop0         0      0         1  1 /cdrom/casper/filesystem.squashfs

You can use the created image for whatever purpose you want; for example, you can use it as a virtual USB drive:

sudo losetup loop1 image.img

Opening Files:

screenshot10

screenshot11