Skip to content
Compare payload ranges after different file headers with cmp

Compare payload ranges after different file headers with cmp

November 23, 2026

Two binary exports can contain the same payload after headers of different lengths. GNU cmp can skip a separate prefix in each file and compare a bounded number of bytes without creating extracted copies.

Run the example

Tested on Linux with GNU Bash 5.2.37, coreutils 9.7, grep 3.11 and diffutils 3.10. Use one Bash session and a text editor. Create a disposable working directory before saving the source:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Save as demo_linux_cmp_bounded_payload_ranges.sh:

set -euo pipefail
export LC_ALL=C
fixture_dir="$(mktemp -d)"
trap 'rm -f -- "$fixture_dir/a.bin" "$fixture_dir/b.bin"; rmdir -- "$fixture_dir"' EXIT
cd -- "$fixture_dir"
printf 'AApayloadX' > a.bin
printf 'BBBBpayloadY' > b.bin
if cmp -s -i 2:4 -n 7 -- a.bin b.bin; then
  printf 'Seven-byte payload: equal\n'
else
  status=$?
  printf 'Unexpected payload comparison status: %s\n' "$status"
  exit 1
fi
if cmp -s -i 2:4 -n 8 -- a.bin b.bin; then
  printf 'Unexpected equality\n'
  exit 1
else
  status=$?
  test "$status" -eq 1
  printf 'Including the next byte: different\n'
fi

Run it:

bash demo_linux_cmp_bounded_payload_ranges.sh

Observed output:

Seven-byte payload: equal
Including the next byte: different

-i 2:4 skips two bytes from the first file and four from the second. -n 7 compares at most seven bytes. Extending the limit by one includes the differing trailer and exercises the negative case. The conditional captures cmp status before another command overwrites it.

Limits and input policy

Exit status 1 means a difference; status 2 means trouble and must not be treated as an ordinary mismatch. A bounded comparison says nothing about bytes outside the selected range. Also verify that both files contain the expected number of bytes: identical short files can compare equal before the requested limit is reached. These fixtures have known lengths and no concurrent writers.

Clean up

Remove the saved script and the empty working directory in the same Bash session:

rm -- demo_linux_cmp_bounded_payload_ranges.sh
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its contents before removing anything else.

Reference

Official documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on