5

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. May 30, 2017 at 21:01
  • You might be looking for a "loop" device.
    – phk
    May 31, 2017 at 7:59
  • 1
    @roaima yup, creating is one thing, mounting is another, bot to reopen Jan 29, 2021 at 8:48

1 Answer 1

7

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.

2
  • 2
    These days, you can even do the mount file.img /mnt/point and mount will create the loop device by itself. May 30, 2017 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. May 30, 2017 at 23:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .