Loop device — a file as a disk
A loop device shows a regular file to the system as a disk: you can partition, format and mount it.
Cheat sheet
8 commands Printable version-
truncate -s 512M disk.imga 512 MiB file -
sudo losetup -f --show disk.imgattach it: /dev/loop0 -
sudo losetup -fP --show disk.imgwith partitions: loop0p1… -
losetup -lwhat is attached to what -
losetup -j disk.imgwhich device a file is on -
sudo losetup -d /dev/loop0detach -
sudo mount -o loop image.iso /mntmount an image directly -
lsblk -e 7list disks without loops
Overview
A loop device is a block device /dev/loopN backed by a regular
file. Whatever is written to the device ends up in the file. You treat it like a disk:
partition it (fdisk-parted), create a filesystem (mkfs), mount it (mount).
What it is for:
- practice partitioning and mounting without touching real disks — this is how the trainer's disk exercises are built;
- open an image: an ISO, a partition image, a filesystem backup;
- snap packages on Ubuntu: every snap is mounted through a loop, which is why
lsblk often lists many
loopN.
The attachment lasts until a reboot or losetup -d. The kernel shows partitions on a
loop device only if it was attached with -P: /dev/loop0p1, /dev/loop0p2.
Recipes
4A filesystem image without partitions
Clean up afterwards
Attach an image at boot
An /etc/fstab line with the loop option — mount attaches the file at boot.
Troubleshooting
5failed to set up loop device: Permission denied
losetup: disk.img: failed to set up loop device: Permission denied — only root
can attach devices. Run it with sudo.
There is no /dev/loop0p1
The device was attached without -P, so the kernel did not read the table. Re-read it
with sudo partprobe /dev/loop0, or detach and attach again with -fP.
losetup: cannot find an unused loop device
No free devices are left, usually because of forgotten attachments. Check
losetup -l and detach the extra ones with losetup -d.
The file is deleted but the space did not come back
The file is still attached to a loop device. Find it in losetup -l (it is marked
(deleted)) and detach it — the space is freed.
losetup -d did not detach the device
The device is mounted. losetup -d only marks it (the AUTOCLEAR column in
losetup -l turns to 1), and it is detached after umount. A second losetup -d
answers detach failed: No such device or address — the device is already gone.
Danger zone
1One file, two devices
losetup -f does not check whether the file is already attached. Two devices on one
file, each mounted, corrupt the filesystem. Check losetup -j file before attaching.
See also
Found an inaccuracy? Report an error in the article