Create and Inspect Safe Loop Devices with losetup
Mount a disk image with losetup straight off the shelf and you can end up writing to something meant only to inspect. You will attach a disk image to a loop device, inspect the association, and detach it without changing the image.
The route
Jump straight to the step you need, or tick off Done means at the end.
Allow about fifteen minutes. You need a Linux shell, losetup from util-linux, and a regular file containing the image. Creating or detaching a loop device normally needs elevated privileges. The examples use sudo only for those operations; listing information may work as an ordinary user, although the manual warns that non-root users cannot see all fields.
The local manpage is for util-linux 2.39.3. The losetup found first in this environment is the Linuxbrew binary and reports util-linux 2.41.3, so check the command on your own host before relying on version-specific output. The options used here are present in both versions.
1. Check the command and the image
Start with read-only checks. Replace /path/to/image.img with an existing image file. None of this creates a device or alters the image:
$ command -v losetup
/usr/sbin/losetup
$ losetup --version
losetup from util-linux 2.39.3
$ stat --format='%F %s bytes %n' /path/to/image.img
regular file 1073741824 bytes /path/to/image.img
Your path and version will differ. If stat cannot read the file, stop and fix the path or permissions. Do not create an empty replacement with shell redirection: an accidental > can truncate an image before losetup ever runs.
Checkpoint
You have an image whose size and path you recognise, and losetup --version identifies the binary that will run.
2. Inspect existing loop devices
Use the current list format rather than the deprecated comma-delimited form produced by losetup -a. JSON is convenient for scripts and makes the backing file explicit:
$ losetup --list --json
{
"loopdevices": [
{
"name": "/dev/loop0",
"ro": true,
"back-file": "/var/lib/example/base.img",
"log-sec": 512
}
]
}
The exact fields and device list are host-specific. For a shorter human-readable check, select columns explicitly:
$ losetup --list --noheadings --output NAME,BACK-FILE,RO
/dev/loop0 /var/lib/example/base.img 1
A loop device may already be in use by a service, a container runtime or a desktop tool. Record what you find before adding another association.
Warning
Do not use --detach-all as a tidy-up shortcut. It removes every loop association visible to the command and can disrupt unrelated mounts or services.
3. Attach the image read-only
Attach the chosen image to the first unused loop device with --find, ask for its name with --show, and prevent a second association for the same file with --nooverlap:
$ sudo losetup --find --show --read-only --nooverlap /path/to/image.img
/dev/loop7
The printed device name is the value to use in later commands. Save it in a shell variable only after checking that it looks like a loop device:
$ LOOPDEV=/dev/loop7
$ case "$LOOPDEV" in /dev/loop[0-9]*) ;; *) echo 'unexpected loop device name' >&2; exit 1;; esac
$ sudo losetup --list --output NAME,BACK-FILE,RO "$LOOPDEV"
NAME BACK-FILE RO
/dev/loop7 /path/to/image.img 1
RO shows as 1 for a read-only association. That protects writes through the loop device, but it is not a substitute for checking where the image came from. Treat an image from an untrusted source as untrusted data, and do not mount it read-write merely because a tool reports a filesystem.
The setup operation with --find is not atomic when several processes race to allocate a device: util-linux limits its internal attempts to 16 and provides no lock. If multiple jobs create loop devices concurrently, serialise the allocation with a lock such as flock in the surrounding automation.
Checkpoint
losetup --list shows your exact image, the expected loop device, and RO=1.
4. Use the device without guessing its boundaries
A loop device maps the image file as a block device. It does not automatically mount a filesystem, scan partitions or validate the image. Ask a read-only inspection tool what is present first:
$ sudo lsblk --noheadings --output NAME,TYPE,SIZE,RO,FSTYPE "$LOOPDEV"
loop7 loop 1G 1 ext4
- Partition table present? Attach with
--partscanwhen creating the loop device, then inspect the resulting partition nodes. - Sector size matters. The manpage documents a default of 512 bytes and says to combine
--sector-sizewith--partscanwhen the image needs another sector size. Do not add either option by habit; establish the image layout first. - Offset and size limit. For an image whose useful data starts later,
--offsetmoves the data start by a byte count and--sizelimitrestricts the visible range after that offset. Both accept suffixes such asKiBandMiB. Verify them in the listing before exposing the device to another program, because they are easy to get wrong.
If the backing file grows while it is associated, use sudo losetup --set-capacity "$LOOPDEV" to ask the kernel to reread its size. This is a capacity update, not a filesystem repair: the application using the device still needs to understand the change.
5. Find an existing association
When you have only the image path, query its associations instead of allocating another loop device:
$ sudo losetup --associated /path/to/image.img
/dev/loop7
Warning
Without --nooverlap, multiple independent loop devices can point at one file. The manual warns that this can cause data loss, corruption and overwrites, especially when one user expects changes made through another association to be invisible. With --nooverlap, a setup request reuses an existing device for the same backing file instead.
6. Detach the device and recover cleanly
Before detaching, stop programs using the loop device and unmount any filesystem mounted from it. Check for mounts before changing state:
$ findmnt --source "$LOOPDEV"
$ sudo losetup --list --output NAME,BACK-FILE,RO "$LOOPDEV"
NAME BACK-FILE RO
/dev/loop7 /path/to/image.img 1
If findmnt prints a mount, unmount it during an appropriate maintenance window. Do not detach a device behind a live service just to make it disappear from the list.
Once the device is no longer needed, detach exactly the device you recorded:
$ sudo losetup --detach "$LOOPDEV"
$ sudo losetup --list --output NAME,BACK-FILE "$LOOPDEV"
losetup: /dev/loop7: failed to use device: No such file or directory
The final command is an optional negative check: a missing device is the expected result after a successful detach. Since Linux 3.7, the kernel can lazily destroy a busy loop device, so a detach may succeed while the kernel marks the device for automatic clearing; the process using it must still be stopped before you consider the work complete.
Recovery
If you detached the wrong device, there is no undo that restores its previous association. Reattach the original image deliberately, preferably read-only, after confirming that no other process has claimed the device:
$ sudo losetup --find --show --read-only --nooverlap /path/to/image.img
/dev/loop7
Done means
- Checked the actual
losetupbinary and util-linux version on the host. - Inspected existing associations before allocating a device.
- Attached the image with
--read-onlyand--nooverlapwhere inspection is the goal. - Verified the loop device name, backing file and read-only flag.
- Avoided
--detach-allfor a single-image cleanup. - Stopped users and unmounted filesystems before detaching the exact device.