FIELD NOTES / UNIX & LINUXNew tools on weekdays. Beyond the man page.
$unexpand

unexpand: compress alignment without inventing a contract

Replace runs of blanks with tabs deliberately, while preserving the boundary between a compact view and data whose exact whitespace carries meaning.

THE DEEP DIVE16 MIN READ
01

Start with leading alignment

unexpand reads each named file, or standard input when no file is named, and writes a copy in which eligible blanks are replaced by tab characters. It never edits the input file. With no options, it converts only initial blanks: the spaces and tabs before the first nonblank character on each line. Tabs are placed at stops every eight columns.

Work in a directory where you may create an unexpand-demo subdirectory. mkdir creates it; each && runs the next command only after success; and cd enters it. printf interprets the trusted format: %s inserts each following quoted string and \n ends the line. The shell's > redirection creates report.txt, replacing a file with that name if one already exists. The printf article develops the format-and-data boundary.

The eight spaces before heading reach the first default tab stop, so unexpand replaces them with one tab. The four spaces between ID and OWNER occur after nonblank text, so default mode leaves them unchanged. The screen can make both results look identical; the next section checks the bytes.

TERMINALCommand — disposable lab
mkdir unexpand-demo &&
cd unexpand-demo &&
printf '%s\n' \
  '        heading' \
  'ID    OWNER' > report.txt &&
unexpand report.txt
TERMINALLogical output; the first character is a tab
	heading
ID    OWNER

A rendered tab can resemble spaces. The output label identifies the otherwise invisible byte; use a byte view before drawing conclusions about a file's representation.

02

Prove which blanks changed

od makes the representation visible. -A n suppresses address labels, -t x1 requests hexadecimal one-byte units, and -v prevents repeated rows from being abbreviated. The od article explains why this is a representation of the bytes rather than the bytes themselves.

The pipeline operator | sends unexpand's standard output to od's standard input. The first output byte is 09, a tab, before heading. On the second line, four 20 bytes remain between ID and OWNER because default unexpand stopped looking for convertible blanks after it encountered I. The 0a bytes end the lines.

TERMINALCommand
unexpand report.txt | od -A n -t x1 -v
TERMINALOutput bytes
 09 68 65 61 64 69 6e 67 0a 49 44 20 20 20 20 4f
 57 4e 45 52 0a

In the POSIX locale, blank means a space or tab. Other locales may classify additional characters as blanks, so locale is part of the conversion contract.

03

Compress internal alignment with all mode

The -a flag, also spelled --all by GNU, considers eligible blank runs after nonblank text. It inserts a tab when a sequence of at least two blanks ends at a tab stop and the tab makes the output shorter. It does not replace every space, and a single ordinary space is not automatically a candidate.

Here ID occupies columns zero and one. Six spaces reach column eight, so -a replaces them with a tab. OWNER then occupies columns eight through twelve; three spaces reach column sixteen and become a second tab. The byte view proves that two 09 bytes were introduced.

TERMINALCommand
printf 'ID      OWNER   STATE\n' |
  unexpand -a |
  od -A n -t x1 -v
TERMINALOutput bytes
 49 44 09 4f 57 4e 45 52 09 53 54 41 54 45 0a

Use -a for a compact human-oriented copy only after confirming that tabs are allowed throughout the destination. In tab-separated data, a newly inserted 09 byte is a new field delimiter, not cosmetic compression.

04

Make the tab-stop contract explicit

The portable -t option takes a tab list. A single number is a repeating interval, so -t 4 places stops every four columns. A comma-separated list such as -t 4,8,12 names specific increasing positions. On GNU unexpand, -t implies -a; --first-only can override that implication when only leading blanks should change.

The first command turns both internal runs into tabs on a four-column grid. The second stream has already passed columns four and eight. Its blanks reach the final stop at column twelve and can produce one tab, but blanks after that remain unchanged because an explicit finite list has no later stop. GNU's /N and +N suffixes extend a list after its final explicit stop; those forms are not portable.

The equals sign in --tabs=4 keeps the option and its argument together. --first-only is a GNU long option; POSIX scripts should avoid relying on it and should express the desired default mode without -t when the standard eight-column grid is sufficient.

TERMINALCommand — GNU 9.7 observations
printf 'ID  OWNER   STATE\n' | unexpand -t 4 | od -A n -t x1 -v
printf '1234567890          X\n' |
  unexpand -a -t 4,8,12 |
  od -A n -t x1 -v
printf '        x    y\n' |
  unexpand --first-only --tabs=4 |
  od -A n -t x1 -v
TERMINALOutput bytes
 49 44 09 4f 57 4e 45 52 09 53 54 41 54 45 0a
 31 32 33 34 35 36 37 38 39 30 09 20 20 20 20 20
 20 20 20 58 0a
 09 09 78 20 20 20 20 79 0a

FreeBSD documents -t for unexpand, while OpenBSD's native unexpand deliberately omits it. A script that needs custom stops must identify its target implementations instead of treating one local manual as universal.

05

Retire the numeric compatibility spelling

GNU accepts the older spelling -8 as a compatibility form for an eight-column tab list. Unlike GNU -t 8, the obsolete form does not imply -a. That small difference makes a mechanical replacement unsafe unless the intended scope is stated.

Both commands below convert the eight leading spaces. Only -t 8 also converts the seven internal spaces after x, because -t implies all mode on GNU. New GNU scripts that want the old leading-only behavior can use --first-only -t 8; portable scripts should use the standardized option set supported by every target.

TERMINALCommand — GNU compatibility comparison
printf '        x       y\n' | unexpand -8 | od -A n -t x1 -v
printf '        x       y\n' | unexpand -t 8 | od -A n -t x1 -v
TERMINALOutput bytes
 09 78 20 20 20 20 20 20 20 79 0a
 09 78 09 79 0a

Deprecated syntax is a maintenance risk because its semantics differ from the apparent modern equivalent. Replace it only after testing fixtures with both leading and internal blanks.

06

Do not expect an inverse transformation

The preceding expand article turns tabs into spaces according to tab stops. unexpand chooses a compact tab representation for eligible blanks. Those are projections, not a reversible encoding pair: several different mixtures of spaces and tabs can render at the same columns.

The fixture begins with one space followed by one tab. expand -t 8 produces eight spaces before X. unexpand then chooses the canonical shorter representation, one tab. cmp -s compares the two files without printing differences; status 1 means their bytes differ. The semicolon runs printf regardless of that expected difference, and $? expands to cmp's immediately preceding status.

od confirms the distinction: original.bin begins 20 09, while restored.bin begins only 09. The display can be the same even though a signature, checksum, parser, or forensic comparison sees different data.

TERMINALCommand — expected non-identity
printf ' \tX\n' > original.bin
expand -t 8 original.bin > expanded.txt &&
unexpand -t 8 expanded.txt > restored.bin &&
cmp -s original.bin restored.bin; printf 'cmp_status=%s\n' "$?"
od -A n -t x1 -v original.bin
od -A n -t x1 -v restored.bin
TERMINALOutput
cmp_status=1
 20 09 58 0a
 09 58 0a

Keep originals when byte identity matters. A round trip that preserves screen columns does not preserve provenance, signatures, or the author's whitespace choices.

07

Backspace and Unicode move the stops

GNU unexpand preserves a backspace byte and decrements its column counter. In the first stream, A and B advance to column two, backspace returns the counter to one, and three spaces reach the four-column stop. GNU 9.7 replaces those spaces with a tab but leaves the 08 backspace byte in the output. It does not erase B or emulate a terminal.

The second stream begins with the three-byte UTF-8 encoding of 界. Installed GNU Coreutils 9.7 under C.UTF-8 counts those bytes for this calculation and emits a tab followed by two spaces. GNU Coreutils 9.11 made expand and unexpand multibyte-character aware; 9.12, released September 14, 2026, is the current stable release at review time. Test the installed version, locale name, and character widths rather than copying the 9.7 transcript into a newer environment.

GNU Coreutils 9.12 also fixes a heap-buffer overflow in unexpand -t that could occur when a tab value exceeded SIZE_MAX divided by 16 or when a multibyte blank used more bytes than the configured tab value. The defect arrived with 9.11's multibyte support. GNU systems that process untrusted text with unexpand should run 9.12 or later; input validation and locale selection are not substitutes for that update. The upstream NEWS record describes the fix without assigning a CVE or claiming exploitation, so this article does not invent either.

LC_ALL=C.UTF-8 applies the locale only to the unexpand process on its right. It does not validate or transcode the input. Combining marks, wide characters, carriage returns, and terminal escapes can still make a rendered line disagree with simple column accounting.

TERMINALCommand — GNU Coreutils 9.7 observations
printf 'AB\b   X\n' | unexpand -a -t 4 | od -A n -t x1 -v
printf '界   X\n' | LC_ALL=C.UTF-8 unexpand -a -t 4 |
  od -A n -t x1 -v
TERMINALOutput bytes
 41 42 08 09 58 0a
 e7 95 8c 09 20 20 58 0a

C.UTF-8 is common on Linux but is not a universal locale name. Check locale -a on the deployed host, and treat control bytes as content requiring an escaping viewer rather than as layout.

08

A new tab can become executable syntax

Whitespace can be grammar. A traditional Makefile recipe begins with a tab unless the file explicitly changes its recipe prefix. The fixture contains a target line followed by eight spaces and the word command. It is only sample text and is never passed to make.

Default unexpand changes those eight leading 20 bytes into one 09 byte. If someone saved that transformed copy as a Makefile, the second line could change from invalid or ordinary indented text into recipe syntax. The same mechanism can create delimiters in tab-separated records or change a whitespace-sensitive policy file.

This is useful during an authorized review because the byte view exposes a hidden contract change before a supplied patch is applied. It is not a reason to rewrite the sample. Preserve the submitted bytes, inspect a separate transformed view, and review the parser's actual whitespace rules.

TERMINALCommand — inspect only
printf 'target:\n        command\n' > Makefile.sample
od -A n -t x1 -v Makefile.sample
unexpand Makefile.sample | od -A n -t x1 -v
TERMINALOriginal bytes, then transformed bytes
 74 61 72 67 65 74 3a 0a 20 20 20 20 20 20 20 20
 63 6f 6d 6d 61 6e 64 0a
 74 61 72 67 65 74 3a 0a 09 63 6f 6d 6d 61 6e 64
 0a

Never use a redirection such as unexpand file > file. The shell truncates file before unexpand can read it. Write a separate artifact and replace the original only through a deliberate, verified procedure.

09

Build a compact review view, not sanitized evidence

Long aligned reports can be smaller and easier to compare after blank runs are represented consistently. Create separate views of a trusted baseline and a supplied candidate, then compare the views while retaining both originals. Each && below stops the sequence if the preceding conversion fails.

diff -u requests unified output. --label supplies stable header labels, and the final -- ends diff's option parsing before the two filenames. The diff article explains why status 1 means differences were found rather than an execution failure. Here whitespace compression removes representational noise while the changed privilege remains visible.

This is not sanitization. unexpand can preserve terminal escapes, backspaces, carriage returns, and misleading Unicode. A hostile file may render deceptively after conversion, and two view files that compare equal need not prove that the originals had equal bytes. Use an escaping viewer for untrusted controls and keep the original evidence.

TERMINALCommand — expected difference
printf 'user    privilege\nsvc     read\n' > baseline.txt &&
printf 'user    privilege\nsvc     admin\n' > supplied.txt &&
unexpand -a -t 8 baseline.txt > baseline.view &&
unexpand -a -t 8 supplied.txt > supplied.view &&
diff -u --label baseline.view --label supplied.view -- \
  baseline.view supplied.view
TERMINALRendered output; diff exits 1
--- baseline.view
+++ supplied.view
@@ -1,2 +1,2 @@
 user	privilege
-svc	read
+svc	admin

The output renderer expands the tabbed view for display, so the hunk appears space-aligned here. The stored .view files contain tabs at eligible stops.

10

Reject plausible partial output

With multiple operands, GNU 9.7 diagnoses an unreadable file, continues with a readable one, emits that file's transformed content, and exits nonzero. A downstream consumer that inspects only standard output can therefore accept a plausible but incomplete result.

The parentheses create a subshell so the expected failure and status handling remain contained. Standard output goes to partial.txt, while 2> sends file descriptor 2, standard error, to unexpand.err. $? expands to unexpand's immediately preceding status; printf records it before cat displays the diagnostic. od then proves that partial.txt still contains a tabbed record.

Diagnostic wording varies by implementation and locale. Automation should test the status rather than match this English sentence. In a pipeline, use an appropriate pipefail policy or capture component statuses; the last command's success does not prove unexpand succeeded upstream.

TERMINALCommand — expected failure
printf '        ok\n' > readable.txt &&
(
  unexpand missing.txt readable.txt > partial.txt 2> unexpand.err
  printf 'status=%s\n' "$?"
  cat unexpand.err
  od -A n -t x1 -v partial.txt
)
TERMINALOutput
status=1
unexpand: missing.txt: No such file or directory
 09 6f 6b 0a

Treat any nonzero conversion as a failed artifact even when its output looks useful. Publish or compare a temporary result only after the complete command has succeeded.

11

Write down what a tab means

The portable core is modest: files or standard input, leading-blank conversion on the default eight-column grid, -a for eligible blank runs throughout a line, and -t where the target standard and implementation provide it. GNU adds long options, --first-only, / and + continuation forms, and the obsolete -NUMBER spelling. FreeBSD and OpenBSD expose different option surfaces, so portable scripts must be tested against their actual targets.

Before using unexpand, state whether tabs are permitted data, separators, or syntax; whether only leading blanks or all eligible runs may change; which stops, locale, and implementation define columns; and whether the output is a disposable view or a new source artifact. The expand article asks the inverse-looking question, but neither command preserves an author's original whitespace representation.

For routine administration, keep the original, inspect ambiguous bytes, transform only at a presentation or storage boundary whose contract permits tabs, and reject failed conversion. unexpand is trustworthy when its inserted tabs are an explicit representation choice. It is dangerous when a smaller file is mistaken for the same data.

Back to latest issue
HELP SHAPE THE NEXT ISSUE

What belongs in your toolbox?

Choose a command you want to know better. We start with familiar tools and work toward the less obvious ones.

READER’S CHOICE

What should we cover next?

Vote for a future deep dive, or suggest a command we missed.

One command name, up to 32 characters. Suggestions are reviewed by a person. A new article starts a fresh poll.

Loading poll…