Creating a bootable hard-disk image with Grub2

Here's a shell script for creating a bootable hard-disk image with Grub2 (v2.06). You need parted, kpartx and grub2. It's a derived version of original script here.

# Create the actual disk image - 20MB
dd if=/dev/zero of=disk.img count=20 bs=1048576
 
# Make the partition table, partition and set it bootable.
parted --script disk.img mklabel msdos mkpart p ext2 1 100% set 1 boot on
 
# Map the partitions from the image file
kpartx -a disk.img
 
# sleep a sec, wait for kpartx to create the device nodes
sleep 1
 
# Make an ext2 filesystem on the first partition.
mkfs.ext2 /dev/mapper/loop0p1
 
# Make the mount-point
mkdir -p /mnt
 
# Mount the filesystem via loopback
mount /dev/mapper/loop0p1 /mnt
 
# Copy in the files from the staging directory
# cp -r build/* /mnt
 
# Create a device map for grub
mkdir -p /mnt/boot/grub
echo "(hd0) /dev/loop0" > /mnt/boot/grub/device.map

# Use grub2-install to actually install Grub. The options are:
#   * No floppy polling.
#   * Install grub into the filesystem at our loopback mountpoint.
#   * Install the MBR to the loopback device itself.
grub-install --no-floppy               \
             --target=i386-pc            \
             --root-directory=/mnt    \
             /dev/loop0 -v
 
# Unmount the loopback
umount /mnt
 
# Unmap the image
kpartx -d disk.img
 
 

You can run the image using Qemu.

kvm -hda disk.img
 
 





 

 

 

Comments

Popular posts from this blog

GNU Emacs as a Comic Book Reader

Data Visualization with GNU Emacs

Tinylisp and Multi-threaded Emacs