Use fallocate Command to Create Files of Specific Size in Linux
The fallocate is one of the lesser known commands for creating files. What makes fallocate different then the rest is that it allows you to create files of specific sizes.
Why would you create a file of specific size? One practical use of fallocate is in increasing the swap file in Linux. With fallocate, you can quickly create a swap file of predetermined size.
This is a much quicker way of creating huge files because it allocates uninitialized blocks. This is a lot faster than creating a huge file and filling it with zeroes.
Using fallocate command in Linux
Let’s see how to use the fallocate command. This is the syntax:
fallocate [-o offset] -l length [-n] filename
While there are some advanced usage of fallocate command, let’s focus on creating file of specific size.
Suppose you want to create a file of 10 MB in size, you can use the fallocate command like this:
fallocate -l 10MB my_big_file
The option l determines the size of the file being created. You can use the following for the length of the file:
|KB||KiB or K|
|MB||MiB or M|
|GB||GiB or G|
|TB||TiB or T|
|PB||PiB or P|
|ZB||ZiB or Z|
|YB||YiB or Y|
I hope you know the difference between MB and MiB. An MB (Mega Byte) is 1000*1000 bytes where as MiB (Mebibyte) is 1024*1024 bytes.
I know you probably didn’t read it in your computer class but this has been the standard set by IEC. This is also the reason why when you buy a 32 GB USB, your operating system only sees around 29 GB (29 GiB). Unlike the hard disk manufacturers, operating systems work in the power of 2.
Now that you learned something new, let’s take another example of creating a file of 1 GiB.
fallocate -l 1G my_big_file
Use the ls command with option -h and you can see the size of the file:
-rw-r--r-- 1 abhishek abhishek 1.0G Aug 28 18:41 my_big_file
The same can be achieved with the dd command and there are a lot of discussion over which one is better of the two.
Do you know some other useful example of the fallocate command? Do share it with us in the comments below.