Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
1  
Since the file is sparse, it should only use as much space as stored in your example. –  jordanm Dec 12 '13 at 2: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

2 Answers 2

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

share|improve this answer
up vote 1 down vote accepted

@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 :)

share|improve this answer
    
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 4: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 5:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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