Loop device basics

· 2min · Calvin Yong
Table of Contents

Loop devices can be useful for when you're trying to learn some commands for managing multiple drives (mdadm, LVM, filesystems with multi device support like btrfs and zfs, etc.), encryption (dm-crypt), or filesystems. Sometimes you might not have spare physical hardware to test on, or maybe you might want to try out some commands before actually running them on your actual hardware.

Basics

To show all loop devices:

losetup

Nothing is printed to the screen since we have no loop devices.

First, we make a file of size 1G (or any value you like):

dd if=/dev/zero of=file1.img bs=1G count=1 status=progress

And then make a loop device associated with file1.img:

losetup --find --nooverlap --show file1.img

losetup will print the path of the loop device, like /dev/loop0. You can check loop devices

losetup

You can also use other commands like fdisk -l or lsblk. To detach a loop device:

losetup -d /dev/loop0

To detach all loop devices:

losetup -D

And that's pretty much it. Once you have your loop devices, you can do whatever you want with them, like what you would normally do to drives or external media. Just use /dev/loop0 rather than /dev/sda, like

sudo mkfs.fat -F 32 /dev/loop0

You can experiment with various userspace tools like cryptsetup, mdadm, LVM, and multi device support for filesystems like btrfs and zfs.

On a side note, if you try mounting a file that has a filesystem to a mountpoint, mount will automatically create a loop device for it. It will also automatically detach the loop device when the filesystem is unmounted. You can also run some comamnds like mkfs on the file itself rather than the loop device, but some commands and mounts might fail if they expect to use devices or UUIDs, so I would just stick with running all of the commands on the loop device.

Resources