Typically, we use the touch command to create an empty file.However, when we are troubleshooting or want to test in certain specific scenarios, we may need large files of specific sizes, such as 500 MB or 2 GB. At this time, we can’t just create an empty file and start writing junk text into it. Is there a way to create a new file of a specific size? Below are several methods to create large files for your reference.
Using the dd Command to Create Large Files
The dd command is used for copying and converting files. Its most common use is to create a live Linux USB. The dd command actually writes to the hard disk, and the speed at which the file is generated depends on the read and write speed of the hard disk. Depending on the file size, this command will take some time to complete. Suppose we want to create a text file named rumenz.img with a size of 2 GB, we can execute the following:
dd if=/dev/zero of=rumenz.img bs=2G count=1
We can change the block size and count as needed. For example, we can use bs=1M and count=1024 to obtain a 1024 MB file.
Using the truncate Command to Create Large Files
The truncate command reduces or extends a file to the desired size. Use the -s option to specify the file size. Next, we use the truncate command to create a file of size 2GB.
truncate -s 2G rumenz.img
We can use<span>ls -lh rumenz.img</span> to view the generated file.
By default, if the requested output file does not exist, the truncate command will create a new file. We can use the -c option to avoid creating a new file.
Using the fallocate Command to Create Large Files
The fallocate command is my preferred method for creating large files because it is the fastest way to create large files. Suppose we want to create a 1 GB file, we can execute the following:
fallocate -l 1G rumenz.img
We can use<span>ls -lh rumenz.img</span> to view the generated file.
Conclusion
The files created by dd and truncate are sparse files. In the computer world, a sparse file is a special file that has different apparent file sizes (the maximum size it can expand to) and actual file sizes (how much space is allocated for data on the disk). The fallocate command does not create sparse files, and it is faster, which is why I recommend using fallocate to create large files.
-End-