brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: losetup -P opens the partitions inside a disk image

Disk
~/tips/tip-disk-losetup-partscan-image

sudo losetup -f -P -r --show sdcard.img

Mounts the partitions inside a full disk image file, such as an SD card backup.

An ISO is easy: mount -o loop and you’re in. A full disk image is harder, like a Raspberry Pi SD card copy or a raw VM disk. It starts with a partition table, so there’s no single filesystem to mount. losetup with -P turns the file into a loop device and makes the kernel read that partition table, so each partition gets its own device.

sudo losetup -f -P -r --show sdcard.img
# /dev/loop0
lsblk /dev/loop0
sudo mount -o ro /dev/loop0p2 /mnt/img

-f picks the first free loop device, --show prints which one it took, -P (--partscan) scans the partition table and -r makes the loop device read-only. After that, lsblk shows loop0p1, loop0p2 and so on, and you can mount them like any partition. I’d always add -r when I only want to look inside or copy a few files out, because then nothing can change the image by accident.

When you’re done, unmount and detach:

sudo umount /mnt/img
sudo losetup -d /dev/loop0

Two things from the man page to keep in mind. The partition table is parsed with 512-byte sectors by default, so an image of a disk with 4K sectors needs --sector-size together with --partscan, or the partitions come out wrong. And detaching is lazy since Linux 3.7: losetup -d doesn’t fail when the device is still busy, it marks it to be removed later. So check that the mount is really gone before you move or delete the image file. losetup -a lists the loop devices that are still set up.

Further reading: losetup(8) manual page, mount(8) manual page

More Disk tips sudo e2freefrag /dev/sdb1 sudo smartctl -a --json /dev/sda | jq '.smart_status.passed' lsscsi -s udisksctl power-off -b /dev/sdX du -sh — .[!.]* * 2>/dev/null | sort -h All Disk tips (44) All topics

Link