Every once in a while there comes a time when you need to use a file as raw device
for example when using qemu qcow file or if you want to have your home directory portable and encrypted
in this example i am using one file named my-hd-image.file and 2 Linux partitions inside it . lets start
Creating the raw device file is simply by using dd ( can also be use via qemu-img )
dd if=/dev/zero of=my-hd-image.file bs=1M count=1024
Create partitions inside the new disk using fdisk , in my file
I had created 2 partitions of 512M
Device Boot Start End Blocks Id System my-hd-image.file1 2048 1050623 524288 83 Linux my-hd-image.file2 1050624 2097151 523264 83 Linux
creating the file system using loop devices to be linked to specific offset inside the file
so that each partition will have its own loop device . the offset calculation is in bits
and i am using bc to calculate it fast for me . the offset of each partition is its start block times 512
witch is the block size ( unless you have set a different one upon creation )
Partition my-hd-image.file1 starts at offset 2048
echo "2048 * 512" | bc 1048576
Partition my-hd-image.file2 starts at offset 1050624
echo "1050624 * 512" | bc 537919488
use the calculation offset to map to the loop device
losetup -o 1048576 /dev/loop1 my-hd-image.file losetup -o 537919488 /dev/loop2 my-hd-image.file
Now we can format the partition
mkfs.ext4 /dev/loop1 mkfs.ext4 /dev/loop2
all is left to do is mount the partitions
root@# mkdir /mnt/my-hd-partition-1 root@# mkdir /mnt/my-hd-partition-2 root@# mount /dev/loop1 /mnt/my-hd-partition-1 root@# mount /dev/loop2 /mnt/my-hd-partition-2
To remove the device just use unmount and to release the loop device
you will need to use losetup
umount /mnt/my-hd-partition-2 umount /mnt/my-hd-partition-1 losetup -d /dev/loop1 losetup -d /dev/loop2