Bootable grub USB stick (EFI and BIOS for Intel)

I'm using grub version 2.02\~beta2-2.

I want to make a USB stick that's capable of booting Intel architecture EFI machines, both 64-bit (x86_64) and 32-bit (ia32). I'm starting from a USB stick which is attached to a running debian system as /dev/sdX. I have nothing that i care about on that USB stick, and all data on it will be destroyed by this process.

I'm also going to try to make it bootable for traditional Intel BIOS machines, since that seems handy.

I'm documenting what I did here, in case it's useful to other people.

Set up the USB stick's partition table:

parted /dev/sdX -- mktable gpt
parted /dev/sdX -- mkpart biosgrub fat32 1MiB 4MiB
parted /dev/sdX -- mkpart efi fat32 4MiB -1
parted /dev/sdX -- set 1 bios_grub on
parted /dev/sdX -- set 2 esp on

After this, my 1GiB USB stick looks like:

0 root@foo:~# parted /dev/sdX -- print
Model:  USB FLASH DRIVE (scsi)
Disk /dev/sdX: 1032MB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags: 
Number  Start   End     Size    File system  Name      Flags
 1      1049kB  4194kB  3146kB  fat32        biosgrub  bios_grub
 2      4194kB  1031MB  1027MB               efi       boot, esp
0 root@foo:~# 

make a filesystem and mount it temporarily at /mnt:

mkfs -t vfat -n GRUB /dev/sdX2
mount /dev/sdX2 /mnt

ensure we have the binaries needed, and add three grub targets for the different platforms:

apt install grub-efi-ia32-bin grub-efi-amd64-bin grub-pc-bin grub2-common
grub-install --removable --no-nvram --no-uefi-secure-boot \
    --efi-directory=/mnt --boot-directory=/mnt \
grub-install --removable --no-nvram --no-uefi-secure-boot \
    --efi-directory=/mnt --boot-directory=/mnt \
grub-install --removable --boot-directory=/mnt \
    --target=i386-pc /dev/sdX

At this point, you should add anything else you want to /mnt here! For example:

And don't forget to cleanup:

umount /mnt

Tags: bios, efi, grub, tip