4

I want to do a few experiments on the btrfs file system, but I don't want to make any changes to my existing partitions, and I want full control over things like device size.

Is it possible to create a file that looks like a block device that I can mount and unmount, and that will act like a block device such as running out of space?

3
  • 3
    @nwilder I don't think it's a duplicate, although it does seem quite close. It's like the two questions are asking similar things, but working from opposite starting points.
    – roaima
    May 30 '17 at 21:01
  • You might be looking for a "loop" device.
    – phk
    May 31 '17 at 7:59
  • 1
    @roaima yup, creating is one thing, mounting is another, bot to reopen Jan 29 at 8:48
4

The loop device is what you need for this. Run these commands as root:

truncate -s1G 1GB.img  # Sparse allocation of a 1GB file
ld=$(losetup --show --find 1GB.img); echo "$ld"

You will now have a loop device (for example, /dev/loop0) that you can treat as a block device.

mkfs -t btrfs "$ld"    # Device that was returned from losetup

mkdir -p /mnt/dsk
mount "$ld" /mnt/dsk

When you've finished, tidy up again

umount /mnt/dsk
losetup -d "$ld"
rm 1GB.img

If you want to create a partition table on the block device, make sure you always include the --partscan flag on the losetup command. This will create the associated devices, for example, /dev/loop0p1.

3
  • You don't need to allocate the space, let alone write zeros on it. truncate -s1G 1G.img also works (and takes no space on disk initially). May 30 '17 at 21:25
  • 1
    These days, you can even do the mount file.img /mnt/point and mount will create the loop device by itself. May 30 '17 at 21:27
  • @StéphaneChazelas ah yes, truncate is a much better option for a filesystem image, thank you. (For throwaway scripts I too often forget about truncate.) Re mount, the question asked for a block device, so I offered the result from losetup.
    – roaima
    May 30 '17 at 23:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.