In this lesson, you will learn how to treat a simple file on your disk as if it were a physical hard drive by using loop devices.
The Virtual Block Device
When we work with physical storage, we usually deal with hardware like /dev/sda or /dev/nvme0n1. However, Linux allows us to create "virtual" block devices. A loop device acts as a translator: it maps a regular file (an image) to a block device interface, allowing the kernel to interact with the file as if it were a partitioned disk or a raw filesystem.
This is incredibly useful for portable storage, testing ISOs, or creating encrypted virtual disks without needing extra physical partitions.
Attaching and Mounting
To use this, we first need to "attach" our file to a loop device. You can do this automatically using the mount command with the -o loop option.
Imagine you have a file named my_storage.img that contains an Ext4 filesystem. You can mount it directly to a directory like this:
# Create a mount point
sudo mkdir /mnt/virtual_disk
# Mount the image file
sudo mount -o loop my_storage.img /mnt/virtual_disk
Behind the scenes, the kernel assigns a device like /dev/loop0 to my_storage.img. If you run lsblk after running that command, you will see /dev/loop0 listed, showing that the kernel now treats that file as a block device.
Cleaning Up
Once you are finished, you do not need to manually detach the loop device. Simply unmounting the directory is enough:
sudo umount /mnt/virtual_disk
The system will automatically release the loop device, making it available for the next image you need to mount. This abstraction layer is what enables modern system installers and container images to remain portable and easy to manage without altering your physical partition table.
Key Takeaway: A loop device allows the kernel to treat a regular file as a block device, enabling you to mount filesystems stored inside images as easily as physical disks.