Linux – How to merge 2 disk images into one with 2 partitions

command linefdisklinuxqemuroot

I have 2 (relatively small) disk images for qemu (raw format) containing different filesystems (say fat and ext4).

I want to put them into an usb stick as two different partitions so that I can plug it in a pc and boot from there.

I could do it with fdisk and dd but that would require root access and manual intervention (this is going to be a frequent activity in the next months.

How can I automate the task?
Can I avoid sudo and root access?

Currently the disk images are created during our continuous integration process and do not require root access or manual intervention but I cannot find a way to merge these two disks to satisfy this new requirement.

edit

What I need to automate is not the partition of an actual usb key, but the creation of a raw disk image that can be written into the usb key with a single sudo dd .... The disk image should already contains the partitions filled with the data (preserving permissions).

What I cannot grasp is why I should need root to write a raw disk image.

Best Answer

You dont need root. You can run "fdisk someimage.hdd" and as long as you have access to that file, you're fine. You can also dd to parts of that file that correspond to partitions, using offset and notrunc parameters to dd.

Specifying the offsets manually is quite more inconvenient compared to using partition devices with dd though. This is where root access can come in handy - you can use the "losetup" command to create loopback block devices for your image and its partitions.

Still, those offset calculations won't vary each time you repeat the exercise if you don't change the partition sizes, so if you figure them out once you can reuse them for the future.

And there is one other way - after you make the image once and have figured out the offsets, you can extract the start of the disk image containing the partition table as a separate file and not need to use fdisk and dd for your future image rebuilds - just concatenate ("cat") the partition table and the two partition images into a disk image. (In some cases you might need to cat also a disk-suffix file after the partitions similar to the disk-prefix file containing the partition table, as there might be a backup partition table at the end of the disk.)

Related Question