install GRUB onto a disk image

1. Create disk image

<!-- lang: shell -->
dd if=/dev/zero of=disk.img bs=1M count=300
fdisk disk.img

new toggle boot

2. Loop mount disk image

<!-- lang: shell -->
sudo losetup --show --find disk.img

3. Get the major and minor numbers of the loop device, and the size (in bytes) of the disk

<!-- lang: shell -->
ls -l /dev/loop0
ls -l disk.img

4. Create a device-mapper node

<!-- lang: shell -->
echo '0 614400 linear 7:0 0' | sudo dmsetup create hda
ls -l /dev/mapper/hda

5. Use kpartx to create device-mapper nodes for the partitions on the disk image

<!-- lang: shell -->
sudo kpartx -a /dev/mapper/hda
ls -l /dev/mapper/hda*

6. Make fs for the partitions

<!-- lang: shell -->
sudo mkfs.ext4 /dev/mapper/hda1

7. Mount the root partition

<!-- lang: shell -->
sudo mount /dev/mapper/hda1 /mnt/part1

8. Create a device.map for grub-install to use

<!-- lang: shell -->
sudo mkdir -p /mnt/part1/boot/grub
sudo vim /mnt/part1/boot/grub/device.map
(hd0) /dev/dm-0
(hd0,1) /dev/dm-1
(hd0,2) /dev/dm-2

9. Install GRUB

<!-- lang: shell -->
sudo grub-install --no-floppy --boot-directory=/mnt/part1 /dev/dm-0

10. Cleanup the mass you made

<!-- lang: shell -->
sudo umount /mnt/part1
sudo kpartx -d /dev/mapper/hda
sudo dmsetup remove hda
sudo losetup -d /dev/loop0

11. Examine disk image

<!-- lang: shell -->
file disk.img

你可能感兴趣的:(install GRUB onto a disk image)