How to create a file of a certain size in Linux using terminal (bash)
Sometimes we need to create files (actually generate them) for testing purposes or for checking our scripts or programs, working with file size limits. In linux you don't have program any script; bash is good enough to meet your requirements to achieve your goal. I will show you, how to generate files of any size you need in my Solus system (don't be afraid, all examples are working on every GNU/Linux based systems and distributions);
Creating a file of an approximate size
This is the fastest way to generate a file using truncate command:
$ truncate -s 2M edustorage.txt
We aimed to 2M big filesize, but let's see, what is precize filesize of this generated one:
dima@edustorage ~/test/yobany $ ls -l
total 0
-rw-rw-r-- 1 dima dima 2097152 Apr 28 11:55 edustorage.txt
Creating a file of a precise size
In order you know exactly the size of a file you want to generate, run following command:
$ fallocate -l 7777 file-7777.txt
In this case we create a file file-7777.txt with a precise size (7777 bytes):
$ ls -l
total 8
-rw-rw-r-- 1 dima dima 7777 Apr 28 11:56 file-7777.txt
In case you plant to allocate file with calculated logic of its size, use this example:
$ fallocate -l $(( 2 * 2048 * 1024 )) edustorage.txt