5

I am building a system that gives users certain amounts of disk space. The way I am doing it is:

  • create a file with dd
  • create an ext4 filesystem inside the file
  • mount the file and tell the user program to use the mountpoint as its working directory

I do not want to use the linux quota system as I dont want the users to be local system users.

The above works fine, but it wastes space as the users are not using all of their allowance but the entire allowance has been allocated already.

Is there a command that can do the same thing as dd but not allocate the whole file at once? So I could make a 20gb file, and when its mounted it would report 20gb of space, but it would only physically take up what has been written to it?

Erin Drummond
  • 226
  • 4
  • 8

3 Answers3

9

You can use the seek parameter of dd to create a sparse file:

dd if=/dev/zero of=filesystem.img  bs=1k seek=1024M count=1

would create a file which can get up to 1G in size but will only occupy the necessary space.

Sven
  • 97,248
  • 13
  • 177
  • 225
  • I'm wondering now what file system would be suitable to use inside that. Basically I want the image to take the same amount of data as the files stored inside. According some info online, ext2/3/4 can write towards the end of the device to avoid fragmentation. Any ideas? – Nikolay Dimitrov Jan 19 '18 at 08:18
3

Have a look at sparse files.

dd if=/dev/zero of=file.img bs=1 count=0 seek=1024M

creates a 1024Mb sparse file that can be formatted and mounted as a filesystem. There is more information on sparse files and using them here.

user9517
  • 114,104
  • 20
  • 206
  • 289
-1

In CentOS, you can use qemu tools as below;

qemu-img create -f raw the_filename 5G

K-ICT
  • 11
  • 1
  • 3
    That would require `qemu`, instead of just `dd`, which is available everywhere. Also, I am not sure this creates a sparse file, at least with your options – Sven Oct 05 '17 at 12:46