# Local block device as file (loop device) ###### tags: `loop` `losetup` Create a file as a local block device. #### Steps Use dd to create a empty file for a block device, for example, a 4GB file ``` $ sudo dd if=/dev/zero of=/mnt/disk1 bs=4M count=1024 1024+0 records in 1024+0 records out 4294967296 bytes (4.3 GB, 4.0 GiB) copied, 2.2866 s, 1.9 GB/s ``` Use a loop device to represent the block device (use -f option to find first availabe loop device) ``` $ sudo losetup -fP --show /mnt/disk1 /dev/loop23 ``` *__NOTE__*: use -j option to check which loop device assoicate to the file ``` $ sudo losetup -j /mnt/disk1 /dev/loop23: [66305]:52172815 (/mnt/disk1) ``` ``` $ lsblk | grep loop23 loop23 7:23 0 4G 0 loop ``` *__NOTE__*: use -e option to enable encryption XOR or DES (require DES package added to kernel) Format the loop device ``` $ sudo mkfs.ext4 /dev/loop23 mke2fs 1.46.5 (30-Dec-2021) Discarding device blocks: done Creating filesystem with 1048576 4k blocks and 262144 inodes Filesystem UUID: 79fe6440-8657-4f3e-a77f-5e4388c4ec1f Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912, 819200, 884736 Allocating group tables: done Writing inode tables: done Creating journal (16384 blocks): done Writing superblocks and filesystem accounting information: done ``` Mount the loop device ``` $ mkdir /tmp/loopDisk1 $ sudo mount /dev/loop23 /tmp/loopDisk1 $ df -h /tmp/loopDisk1/ Filesystem Size Used Avail Use% Mounted on /dev/loop23 3.9G 24K 3.7G 1% /tmp/loopDisk1 ``` Umount the loop device ``` $ sudo umount /dev/loop23 $ sudo losetup -d /dev/loop23 ``` #### Reference - https://www.jamescoyle.net/how-to/2096-use-a-file-as-a-linux-block-device - https://www.thegeekdiary.com/how-to-create-virtual-block-device-loop-device-filesystem-in-linux/ - https://unix.stackexchange.com/questions/205541/how-to-atomically-allocate-a-loop-device