Skip to content

Instantly share code, notes, and snippets.

@Dids
Last active March 17, 2025 23:10
Show Gist options
  • Select an option

  • Save Dids/c6fa12602ae812e873db539f71c52a3a to your computer and use it in GitHub Desktop.

Select an option

Save Dids/c6fa12602ae812e873db539f71c52a3a to your computer and use it in GitHub Desktop.
Working with raw disk images with GPT + EFI partition in linux

Creating the disk image

Create a blank disk image

dd if=/dev/zero of=image.img iflag=fullblock bs=1M count=100 && sync

Mount the image

(losetup will list all used loopback devices) (losetup loop4 will mount it on the next available loopback devices, eg n+1)

# NOTE: For experienced users, you can use "losetup -f image.img" to automatically use the next available loop device
losetup
losetup loop4 image.img
losetup

Create the EFI partition on the image

gdisk /dev/loop4
o
y
n
<enter until hex code>
0xEF00
w
y
partprobe /dev/loop4
ls /dev/loop4*

Format the EFI partition

mkfs.fat -F32 /dev/loop4p1

Mount the EFI partition

mkdir /mnt/image
mount /dev/loop4p1 /mnt/image

Copy files to /mnt/image etc.

Unmount the EFI partition

umount /mnt/image

Unmount the image

losetup -d /dev/loop4
losetup

Working with the disk image

This section assumes that you no longer have the image mounted in any way.

Mount the image

# Mount the image as a loopback device first
# -f searches for the next free loop device (no need to manually select one)
# -P triggers a scan for any available partitions in the image
losetup -f -P image.img

# Get the loopback device for the mounted image
LOOP_DEV_PATH=`losetup -a | grep image.img | awk -F: '{print $1;}'`p1

# Mount the EFI partition to a local path (create path first if necessary)
mkdir -p /mnt/image
mount $LOOP_DEV_PATH /mnt/image
ls -lah /mnt/image

Unmount the image

# Unmount the EFI partition
umount /mnt/opencore

# Remove the mount point
# DISCLAIMER: Be careful with this, as you could potentially lose data if unmounting was unsuccessful etc.
rm -rf /mnt/opencore

# Get the loopback device path
LOOP_DEV_PATH=`losetup -a | grep opencore.img | awk -F: '{print $1;}'`

# Remove the loopback device
losetup -d $LOOP_DEV_PATH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment