26

I know I can create and use a loopback device like this:

# Create the file
truncate disk.img --size 2G
# Create a filesystem
mkfs.ext4 disk.img
# Mount to use
mount disk.img /mnt
# Clean up
umount /mnt

However in this case the disk image is fixed at 2GB. It's 2GB when it's empty, and it's 2GB when it's full. It will not grow.

Is there a kind of loopback device that can grow in size? Or, is there a kind of loopback device that only needs as much space that it stores?

phunehehe
  • 20,240
  • 2
    Since the file is sparse, it should only use as much space as stored in your example. – jordanm Dec 12 '13 at 02:58
  • Depending on what you are trying to accomplish with this the tool virt-make-fs might be useful. It can be used to create ext2-images using tar files. – Kotte Dec 12 '13 at 22:37

3 Answers3

19

Create a sparse-file device, using dd.

df -hm # to show where we started
dd of=sparse-file bs=1k seek=102400 count=0 # creates a 100Meg sparsefile
mkfs.ext4 sparse-file
mkdir blah
mount sparse-file blah
cp somefile blah
ls -lahts sparse-file  # The 's' option will report the actual space taken in the first column
ls -lahts blah
df -hm # doublecheck my work
echo 'profit :)'

Reference: wikipedia sparse file article

Anthon
  • 79,293
Stephan
  • 2,911
11

@jordanm's comment nailed it. I assumed that the file size was fixed when I looked at the output of ls -lh disk.img. When I used ls -s disk.img like in @Stephan's answer the real file size is showed. As a test, I created an image file that is larger than my hard drive:

truncate test.img -s 1000G

And it works just fine, which means the answer is in the question :)

phunehehe
  • 20,240
  • Truncate works great, btw, I just thought I'd show an alternate command to create said sparse file, and (depending on your linux distribution and toolset) that you don't necessarily need to use losetup, as 'mount' in it's current incarnation is pretty smart about setting sensible options when you need them. – Stephan Dec 12 '13 at 04:30
  • The bit about mount is interesting. It's just that this time because I also need LUKS (cryptsetup luksFormat /dev/loop0), I need losetup :D – phunehehe Dec 12 '13 at 05:09
  • Another handy linux command to create the sparse file is fallocate(1). – Lloeki Dec 13 '17 at 16:01
3

You can do it manually with either dd seek, or easier, since you use truncate:

truncate -s 100M file
mkfs.ext4 -m0 file
#mount, do whatever
umount /mountpoint
#let's grow it to 200 MB
truncate -s 200M file
e2fsck -f file && resize2fs file
#done

A 2 liner for growing it, hardly calls for automation here, I would dare say :)

Ghanima
  • 880