Normally, we use the touch command to create an empty file.

However, when we are troubleshooting or want to test in some specific scenario, we may need a large file of a specific size, such as 500 MB or 2 GB.

At this point, we can’t just create an empty file and start writing random data to it.

Is there any way to create a new file of a specific size?

Here are a few ways to create large files for your reference.

Creating large files with the dd command

The dd command is used to copy and convert files. Its most common use is to create live Linux USBs.

The dd command is actually written to the hard drive, the speed at which the file is generated depends on the read and write speed of the hard drive, and depending on the size of the file, the command will take some time to complete.

Suppose we want to create a 2 GB sized text file called rumenz.img, we can do the following.

1
dd if=/dev/zero of=rumenz.img bs=2G count=1

We can change the block size and number of blocks as needed. For example, you can use bs=1M and count=1024 to get a 1024 Mb file.

Creating large files with the truncate command

The truncate command shrinks or expands a file to the desired size. Use the -s option to specify the size of the file.

Next, we use the truncare command to create a file of 2GB in size.

1
truncate -s 2G rumenz.img

You can use the ls -lh rumenz.img command to view the generated files.

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 new files.

Creating large files with the fallocate command

The fallocate command is the method I recommend 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 do the following.

1
fallocate -l 1G rumenz.img

You can use ls -lh rumenz.img to view the generated files.

Summary

The files created by dd and truncate are sparse files. In the computer world, sparse files are special files with different apparent file sizes (the maximum size they can scale to) and real file sizes (how much space is allocated for the data on disk).

The fallocate command, on the other hand, does not create sparse files, and it is much faster, which is why I recommend using fallocate to create large files.