How do you create and partition a raw disk image?

First create a blank raw disk image (25GB in this case):

    # dd if=/dev/zero of=disk.img bs=1024k seek=25600 count=0
    0+0 records in
    0+0 records out
    0 bytes (0 B) copied, 2.7301e-05 s, 0.0 kB/s
    # ls -lh
    total 2.0G
    -rw-r--r-- 1 root root  25G Dec 13 11:13 disk.img

Give it a partition table:

    # parted disk.img mklabel msdos

Mount it as a loopback device (the simplest way to define cylinders, heads, and sectors):

    # losetup -f disk.img
    # losetup -a
    /dev/loop0: [0801]:12059103 (/path/to/disk.img)

Check that it seems to be a valid block device:

    # fdisk /dev/loop0

    WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
     switch off the mode (command 'c') and change display units to
     sectors (command 'u').

    Command (m for help): p

    Disk /dev/loop0: 26.8 GB, 26843545600 bytes
    255 heads, 63 sectors/track, 3263 cylinders
    Units = cylinders of 16065 * 512 = 8225280 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0x000db005

    Device Boot      Start         End      Blocks   Id  System

Then use fdisk to partition it as you wish:

    # fdisk /dev/loop0

When you're done you need to unloop the device (it will need unmapping and unmounting first):

# losetup -d /dev/loop0

Fully automated procedure

Create a my.img image with a single ext4 partition:

sudo apt-get install kpartx
img='my.img'
dd if=/dev/zero of="$img" bs=512 count=131072
printf 'o\nn\np\n1\n\n\nw\n' | fdisk "$img"
sudo kpartx -av "$img"
sudo mke2fs -t ext4 /dev/mapper/loop0p1
mkdir d
sudo mount /dev/mapper/loop0p1 d
# Do something to the ext partition.
sudo touch a
sudo umount d
sudo kpartx -dv "$img"

Tested on Ubuntu 14.04.

The "hard" parts are:

  • mounting the image file with multiple loop partition devices. Here we used kpartx, but there are other methods: How can I mount a partition from dd-created image of a block device (e.g. HDD) under Linux?

  • creating partitions non-interactively. Here we just piped into fdisk as mentioned at: Creating and formating a partition using a bash script