How to clone a specific partition of a qemu raw disk file to a physical partition

I have a raw disk file as bellow

$fdisk -l Monterey.img

Disk Monterey.img: 14 GiB, 15032385536 bytes, 29360128 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: B0853EBC-902A-41B6-8BEB-C533A09C0376

Device         Start      End  Sectors  Size Type
Monterey.img1     40   409639   409600  200M EFI System
Monterey.img2 409640 29097943 28688304 13,7G Apple HFS/HFS+

It has 2 partitions, 1st for EFI (200MB), 2nd for MacOS installer data

And I have a SSD disk (GUIID type formatted)

~$ lsblk
sda           8:0    0 447,1G  0 disk 
├─sda1        8:1    0   190M  0 part 
├─sda2        8:2    0 152,6G  0 part /mnt/sda2
├─sda3        8:3    0    96M  0 part 
├─sda4        8:4    0   9,6G  0 part 
├─sda5        8:5    0  15,5G  0 part 
├─sda6        8:6    0  15,5G  0 part 
├─sda7        8:7    0 156,3G  0 part 
└─sda8        8:8    0    97G  0 part /media/minh/M2

I want to clone the 2nd partitions from Monterey.img to sda6 (physical partition of internal SSD),

I have tried with

$sudo dd if=Monterey.img of=/dev/sda6

29360128+0 records in
29360128+0 records out
15032385536 bytes (15 GB, 14 GiB) copied, 253,909 s, 59,2 MB/s

but the result report that unknown type , while other HFS+ partitions are visible and accessible.

Result disk:

Result disk

If the source disk file type is DMG, it can be cloned by DMG2IMG command as below:

$sudo dmg2img -p 2 BaseSystem.dmg /dev/sda6

How can I do that for a raw img type ?

Asked By: MinhNV

||

losetup + dd can do it.

1. find first unused loop device

losetup -f

result for example:

/dev/loop0

2. attach Monterey.img to loop0

losetup /dev/loop0 Monterey.img
partprobe /dev/loop0
lsblk

3. clone

dd if=/dev/loop0p2 of=/dev/sda6
Answered By: bin456789