A disk image can have a logical length of one megabyte while occupying only a few kilobytes on disk. A sparse file has unwritten ranges that read as zeros without necessarily consuming data blocks. When planning a copy or investigating unusually large files, label logical length and reported allocation separately. This experiment shows how to measure both quantities in bytes.

Prerequisites and fixture

Use Bash and GNU coreutils on Linux. Save as sparse.sh in a writable working directory. The script creates a 1 MiB file in its own temporary subdirectory, then writes a single byte halfway through without shortening the file. It removes the fixture on exit. Do not substitute an existing disk image for the temporary path.

#!/usr/bin/env bash
set -eu
d=$(mktemp -d ./sparse-demo.XXXXXX)
trap 'rm -rf -- "$d"' EXIT
p="$d/image.bin"
truncate -s 1048576 -- "$p"
printf 'X' | dd of="$p" bs=1 seek=524288 conv=notrunc status=none
logical=$(stat -c %s -- "$p")
blocks=$(stat -c %b -- "$p")
block_size=$(stat -c %B -- "$p")
apparent=$(du --apparent-size -B1 -- "$p")
allocated=$(du -B1 -- "$p")
[[ "$logical" == 1048576 ]]
[[ "${apparent%%$'\t'*}" == "$logical" ]]
[[ "${allocated%%$'\t'*}" == "$((blocks * block_size))" ]]
printf 'logical=%s allocated=%s\n' "$logical" "$((blocks * block_size))"

Run and compare

bash sparse.sh

Example output on the tested filesystem follows. The allocation number can vary.

logical=1048576 allocated=4096

stat %s reads the logical byte length. stat %b gives the reported count of allocated blocks and %B gives the byte size for that count. The script compares their product with ordinary du -B1. It also compares the logical length with du --apparent-size -B1. Setting the output unit explicitly avoids an apparent disagreement caused by display scaling. The tab split is for this controlled single-file output.

Investigate a different result

If both numbers match on your volume, the script can still pass. Its assertions compare independent readings of the same quantities, not a requirement that all filesystems allocate sparse extents identically. Check that you are using GNU tools if an option is rejected. If you remove conv=notrunc or change the fixture's write position, recheck the logical length before interpreting the allocation. Also distinguish the regular-file experiment from directory totals, where entries and hard-link accounting can affect the report.

When estimating space after copying, measure on the destination. The source measurement does not prove that another copy tool, storage layer, archive format or filesystem will preserve holes. Conversely, when estimating how much sequential data an application can read, the logical length is the useful figure even if most bytes are unwritten zeros.

GNU Coreutils manual for du · GNU Coreutils manual for stat · Java Samples Linux tutorials