How to boot an ISO in your hard drive using Grub

#linux

Story

My last laptop broke its keyboard :/, and I’ve got the opportunity to use a MacBook Pro early 2015, the one of this picture:

Screen shot of "About This Mac"

I remember I have got many problems migrating from Linux to macOS in the past. I have always used a case-sensitive filesystem in Linux (of course), and in macOS, by default, it is not case-sensitive.

I’m not telling you to use a case-sensitive filesystem in macOS. I know that there are some problems with other software (one that I’ve heard about is Photoshop). However, I’m a Linux user, and I know the same problems could happen again.

This time I searched how to reinstall macOS using a thumb drive, although I got an idea that I could do the same thing using the “macOS Recovery” option. It is the same thing as booting a thumb drive.

I wondered if I could be able to do the same recovery option in Linux.

The restrictions for the recover option are: it has to be an ISO, and I can be able to install without a good internet connection. The former restriction is because it is easy to update an ISO, the latter is, worst case scenario, I don’t have to download a complete operating system again.

The ISO of my choice is Ubuntu (18.04).

In my current setup, I created a partition for the ISO and another for the /boot directory, 2GB and 512MB, respectively. I have never created a partition for /boot before, this time I thought it could be a good idea.

I tried many options by dd an ISO into my sda2, but nothing worked, then I deleted the sda2 and sda3 and created only one called sda2.

In summary, my setup is a sda2 fat partition (aka, mkfs.fat -F 32).

Hands on!

Create or, probably, update the file /etc/grub.d/40_custom with this content:

#!/bin/sh
exec tail -n +3 $0

menuentry "Ubuntu" {
  set isofile="/ubuntu-18.04-desktop.amd64.iso"
  loopback loop (hd0,2)$isofile
  linux (loop)/casper/vmlinuz boot=casper iso-scan/filename=$isofile quiet splash noprompt noeject
  initrd (loop)/casper/initrd.lz
}

You might want to remove quiet splash and add toram.

hd0 of (hd0,2) stands for sda and 2 for 2. Using sdb1 it could be (hd1,1), for instance.

Now run:

# grub-mkconfig -o /boot/grub/grub.cfg
# grub-install /dev/sda

If the ISO is in an ext4 partition (I have not tested) you have to add insmod ext2 after the line with menuentry.

Just a final recomendation: test this boot at least once.

IMPORTANT: if you delete your main linux you have to keep the /boot/grub directory, because grub still reads it on boot.

My recommendation is to set a /boot partition of 2.5GB or what is better for your iso.

References