I want to partition a raw disk image with the following commands:

#creating the blank image
$ dd if=/dev/zero of=example.img bs=1M count=50

#write the partition table
$ parted example.img mktable msdos

#creating partition but not the file system
#creating fat32 primary partition 1 to 15 MB
$ parted example.img mkpart p fat32 1 15
#creating ext3 primary partition 16 to end
$ parted example.img mkpart p ext3 16 -0

These commands don't create a file system. How could I do that? I am trying the mkfs command in parted but it is showing no command found. How could I create file system externally?


Use the command kpartx to create a loopback device that can then be formatted.

kpartx -a /path/to/imagefile.img  # Presents partitions from the image file
mkfs.vfat /dev/mapper/loop0p1   # Format partition 1
mkfs.ext3 /dev/mapper/loop0p2   # Format partition 2
kpartx -d /path/to/imagefile.img  # Unmaps the partitions from the image file

Related kpartx examples here


Recent versions of losetup gained -P option. Quote from man 8 losetup:

-P, --partscan
          Force the kernel to scan the partition table on a newly created loop device.

Doing losetup -f my_partitioned.img not only creates /dev/loop0, but also partition devices:

$ ls -l /dev/loop0*
brw-rw---- 1 root disk   7, 0 Oct  5 18:43 /dev/loop0
brw-rw---- 1 root disk 259, 0 Oct  5 18:43 /dev/loop0p1
brw-rw---- 1 root disk 259, 1 Oct  5 18:43 /dev/loop0p2

With the usual mkfs commands, such as mkfs.ext4. You will need to use losetup to associate a loopback device with the file though in order to have somewhere to point mkfs to. You also may need to use partprobe to recognize the partitions on the loop device.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.