Loopback filesystems are very interesting components of Linux-like systems. We usually create filesystems on devices (for example, disk drive partitions). These storage devices are available as device files such as /dev/device_name. In order to use the storage device filesystem, we mount it at a directory called a mount point . On the other hand, loopback filesystems are those that we create in files rather than a physical device. We can then mount those files as filesystems at a mount point. This essentially lets you create logical “disks” inside a file on your physical disk!
losetup is a system administration command. It is used to set up and control loop devices. It can attach a loop device to a regular file or block device, detach a loop device, or query a loop device. A loop device can be used to mount an image file as if it were a normal device.
Command line Options
Option | Description |
---|---|
-d | Detach specified loopdevice. |
-e encryption, -Enumber | Use specified kernel encryption module when performing writes and reads. (Usually NONE, DES, and XOR.) |
-o offset | Start reading data at offset bytes from the beginning of file. |
-p fd | Read the passphrase from file descriptor fd. |
An ISO file is an archive of an optical media. We can mount ISO files in the same way that we mount physical disks by using loopback mounting. We can even use a nonempty directory as the mount path. Then, the mount path will contain data from the devices rather than the original contents until the device is unmounted. For example:
# mkdir /mnt/iso # mount -o loop linux.iso /mnt/iso
Now perform operations using files from /mnt/iso. ISO is a read-only filesystem.
If you encounter below error while running the losetup command:
losetup: command not found
you may try installing the below package as per your choice of distribution.
Distribution | Command |
---|---|
OS X | brew install util-linux |
Debian | apt-get install mount |
Ubuntu | apt-get install mount |
Alpine | apk add util-linux |
Arch Linux | pacman -S util-linux |
Kali Linux | apt-get install mount |
CentOS | yum install util-linux |
Fedora | dnf install util-linux |
Raspbian | apt-get install loop-aes-utils |
losetup Command Examples
1. List loop devices with detailed info:
# losetup -a
2. Attach a file to a given loop device:
# losetup /dev/loop /path/to/file
3. Attach a file to a new free loop device and scan the device for partitions:
# losetup --show --partscan -f /path/to/file
4. Attach a file to a read-only loop device:
# losetup --read-only /dev/loop /path/to/file
5. Detach all loop devices:
# losetup -D
6. Detach a given loop device:
# losetup -d /dev/loop