Skip to content

Instantly share code, notes, and snippets.

@ammarshah
Created October 6, 2025 04:26
Show Gist options
  • Select an option

  • Save ammarshah/099232a921a7546a9736694ec3552820 to your computer and use it in GitHub Desktop.

Select an option

Save ammarshah/099232a921a7546a9736694ec3552820 to your computer and use it in GitHub Desktop.
How to Create Dummy/Test Files in Linux

How to Create Dummy/Test Files in Linux

TL;DR

  • fallocate: Allocates actual disk space (reserves it upfront)
  • truncate: Changes file size without allocating space (creates sparse files)

What are "Sparse Files"?

Sparse files have "holes" - regions that claim to exist but have no actual data. When read, the OS returns zeros for holes without storing them on disk. This saves space but may cause issues if the disk fills up later when you try to write real data.

Usage Examples

fallocate - Pre-allocate disk space

# Create a 100 MB file with actual disk space reserved
fallocate -l 100M my_file.mp4

# Increase to 500 MB (allocates additional space)
fallocate -l 500M my_file.mp4

# Shrink? Use truncate instead!
truncate -s 300M my_file.mp4

truncate - Set file size (sparse)

# Create a 100 MB sparse file (uses ~0 disk space)
truncate -s 100M my_file.mp4

# Increase to 500 MB (still sparse, instant)
truncate -s 500M my_file.mp4

# Decrease to 300 MB (cuts off the end)
truncate -s 300M my_file.mp4

Check Actual Disk Usage

# Logical size
ls -lh my_file.mp4

# Actual disk space used
du -h my_file.mp4

# For sparse files, these will differ!

Example: Sparse vs Pre-allocated

# Sparse file - claims 1GB but uses 0 bytes
truncate -s 1G sparse.img
du -h sparse.img  # Output: 0

# Pre-allocated file - claims 1GB and uses 1GB
fallocate -l 1G preallocated.img
du -h preallocated.img  # Output: 1.0G

Key Differences

Feature fallocate truncate
Disk space Allocates real disk space Creates sparse files (holes)
Speed Slower (reserves blocks) Instant (just updates metadata)
Guarantees Space is guaranteed available May fail later when writing
Shrinking Can't shrink files Can shrink and grow
Portability Linux-only POSIX (all Unix-like systems)

When to Use Which?

Use fallocate when:

  • You need guaranteed disk space (databases, VMs, torrents)
  • You want to avoid fragmentation
  • Performance matters (prevents "out of space" errors mid-write)
  • You're on Linux

Use truncate when:

  • You need portability across Unix systems
  • You want to quickly create test files
  • You need to shrink files
  • Sparse files are acceptable for your use case

Pro tip: When transferring sparse files over a network, use rsync --sparse to preserve sparseness and save bandwidth!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment