Managing loop devices on CentOS and Fedora Linux hosts

Linux loop devices provide a way to mount ordinary files as block devices. This capability allows you to easily access an ISO image that resides on disk, mount and unmount encrypted devices (the dm-crypt and fuse encryption module may be a better solution for this), or test out new file systems using plain old files.

Linux loop devices are managed through the losetup utility, which has options to add, list, remove and locate unused loop devices. To associate a loop device with a file, you will first need to locate an unused loop device in /dev. This can be accomplished by running losetup with the “-f” (find an unused loop device) option:

$ losetup -f

Once you identify an available loop device, you can associate the loop device with a file by running losetup with the name of the loop device, and the file to associate with the loop device:

$ losetup /dev/loop0 /root/foo

To verify the device is attached, you can run losetup with the “-a” (show all loop devices) or “-j” (show loop devices associate with the corresponding file) option:

$ losetup -a
/dev/loop0: [0801]:12779871 (/root/foo)

$ losetup -j /root/foo
/dev/loop0: [0801]:12779871 (/root/foo)

To access the contents of a loop device, you can use the mount utility to mount the loop device to a directory that resides in an existing file system:

$ mount /dev/loop0 /mnt

This of course assumes that the underlying file contains a valid label and file system (you can run fdisk or parted to create a label, and then use your favorite mkfs variation to create a file system). Once you finish using a loop device, you can remove it by running losetup with the “-d” (remove loop device) option:

$ umount /mnt

$ losetup -d /dev/loop0

$ losetup -a

I have come to rely on loop devices for all sorts of purposes, and their simplicity makes them so so useful!

2 thoughts on “Managing loop devices on CentOS and Fedora Linux hosts”

  1. Excellent! I was looking for something like lofiadm in Solaris, but for Linux. This is useful to mount a DVD ISO as a block device, for example.

  2. mmm… in linux i always have used:

    #mount -o loop file.iso /mountpoint

    Also FYI, you can do this in FreeBSD using:

    # mdconfig -a -t vnode -f file.iso -u 0
    # mount /dev/md0 /mnt

    And tools in Windows.

    Handy post but. I will investigate. Thanks!


Leave a Reply

Your email address will not be published. Required fields are marked *