Create A File And Loop It As A Filesystem in Linux
Associating file systems to storage devices in Linux is called mounting. The mount command is used to attach a file system to a file system hierarchy. To mount, you provide a file system type, a file system, and a mount point.
To demonstrate the capabilities of the Linux file system layer , create a file system in a file within the current file system. This is achieved by creating a file of a given size using dd in other words, a file initialized with zeros, as shown in figure 1.
$ dd if=/dev/zero of=file.img bs=1k count=10000
You now have a file called file.img that is 10MB. Use the losetup command to merge a loop device with the file (making it look like a block device instead of just a regular file within the file system):
$ losetup /dev/loop0 file.img
The file now appears as a block device (represented by /dev/loop0), create a file system on the device with mke2fs. This command spawns a new second ext2 file system of the defined size, as shown in Figure 2.
$ mke2fs -c /dev/loop0 10000
The file.img file, symbolized by the loop device (/dev/loop0), is now mounted to the mount point /mnt/point1 using the mount command. Note the differentiation of the file system as ext2. When mounted, you can consider this mount point as a new file system by using an ls command, as shown in Listing 3.
Figure 3. Creating a mount point and mounting the file system through the loop device
$ mkdir /mnt/point1
As shown in Figure 4, you can aggrandize this process by constructing a new file within the new mounted file system, associating it with a loop device, and creating another file system on it.
Figure 4. Creating a new loop file system within a loop file system
$ dd if=/dev/zero of=/mnt/point1/file.img bs=1k count=1000
From this simple presentation, it is easy to see how powerful the Linux file system is. You can use this same technique to create encrypted file systems with the loop device on a file. This is beneficial to protect your data by metaphorically mounting your file using the loop device when needed.