How to Quickly Create a Large File on Linux
Creating large files can be useful for various testing scenarios, such as:
- Testing upload and download speeds.
- Simulating disk usage.
- Converting files to swap space.
This guide covers two methods to create large files: using the fallocate
command (preferred for speed) and the dd
command.
Method 1: Using fallocate
The fallocate
command creates a large file almost instantly by allocating space directly on the disk.
Example
The following command creates a 10GB file:
$ fallocate -l 10GB /justgeek
Verify the file size:
$ du -sh /justgeek
9.4G /justgeek
Options
Run fallocate --help
to see all available options. Here are some key ones:
-c, --collapse-range
: Remove a range of bytes from the file.-d, --dig-holes
: Replace sections of zeros with holes.-p, --punch-hole
: Create a sparse file by replacing a range with a hole.-l, --length <num>
: Specify file length in bytes.
For more details, check the fallocate
man page.
Method 2: Using dd
The dd
command reads data (usually from /dev/zero
) and writes it to a file. This method is slower than fallocate
but offers more flexibility.
Example: Creating a 1MB File
$ dd if=/dev/zero of=justgeek.txt count=1024 bs=1024
1024+0 records in
1024+0 records out
1048576 bytes (1.0 MB) copied, 0.012 seconds, 82.7 MB/s
Explanation:
if=/dev/zero
: Input source, generating null characters.of=justgeek.txt
: Output file.count=1024
: Number of blocks to copy.bs=1024
: Block size in bytes.
Example: Creating a 1GB File
Multiply the block size by the count to calculate the desired size:
$ dd if=/dev/zero of=justgeek.txt count=1048576 bs=1024
1048576+0 records in
1048576+0 records out
1073741824 bytes (1.0 GB) copied, 19.2 seconds, 53.3 MB/s
To create a file with random data instead of zeros, use /dev/urandom
:
$ dd if=/dev/urandom of=justgeek.txt count=1048576 bs=1024
Conclusion
Both fallocate
and dd
are effective for creating large files on Linux. Use fallocate
for speed, or dd
for flexibility (e.g., generating random data).