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

join: match inventories by identity, not position

Merge ordered text inventories by a declared key, expose missing relationships, and recognize the ordering and duplicate-key assumptions behind the result.

THE DEEP DIVE17 MIN READ
01

Match the first field in two files

Two collectors describe the same accounts. One records numeric IDs; the other records approved deployment scopes. The rows are not in corresponding positions, so placing line 1 beside line 1 would invent relationships. join instead compares a key field and emits pairs whose keys are equal.

Start from a directory where you may create a new join-demo subdirectory. The first command opens an interactive Bash without reading personal startup files: --noprofile and --norc skip those files, and -i requests interactive operation. Paste the remaining lines at the child shell's prompt. export LC_ALL=C gives every later sort and join in this lab the same byte-oriented locale. Leave the child shell with exit when finished.

mkdir creates join-demo and must fail if that name already exists; do not continue with stale fixtures. The && operator runs the next command only when the previous command succeeds. cd makes join-demo the working directory for every later relative pathname. The two printf commands create synthetic, space-separated files. The '%s\n' format prints each following argument and a newline; the > redirections write those lines to accounts and approvals. The printf article explains why the fixed format stays separate from its data. These fixtures are already ordered by username in the C locale.

With no options, join treats the first blank-separated field as the key in each file. It ignores leading blanks, treats runs of blanks as field separators, and writes the shared key followed by the remaining fields from file 1 and then file 2. It reads the files without modifying them.

TERMINALCommand — disposable lab
bash --noprofile --norc -i
export LC_ALL=C
mkdir join-demo &&
cd join-demo &&
printf '%s\n' 'alice 1001' 'bob 1002' 'carol 1003' > accounts &&
printf '%s\n' 'alice prod' 'carol staging' 'erin prod' > approvals &&
join accounts approvals
TERMINALOutput
alice 1001 prod
carol 1003 staging

Alice and Carol occur in both files, so they produce output. Bob and Erin are unpaired and disappear from this default inner join. Unlike paste, which assembles records by position, join compares fields. We will make the ordering contract explicit, then choose what unmatched and duplicate keys should mean.

02

Sort by the same rule used for matching

Join is a streaming merge, not a hash-table lookup. Its two inputs must be ordered on their join fields according to the same comparison rule join will use. As it reads, it advances past the smaller key and combines equal keys. An incompatible order can therefore hide matches or trigger a diagnostic.

Replace the simple fixtures with colon-separated account and access snapshots. Each guarded printf overwrites only the named synthetic file in join-demo. The trailing > targets are shell redirections, not join syntax.

The exported LC_ALL=C setting applies the C locale to both sort processes and every later join, giving all comparisons the same byte-oriented collation. The sort article develops the distinction between ordering, equality, and stability. Here -t ':' selects colon as sort's field separator. The -k 1,1 option makes the key start and end at field 1 instead of continuing through the rest of the line. The space between -k and 1,1 is ordinary option-argument syntax.

The resulting *.sorted files become the inputs for the rest of the lab. Keeping locale, delimiter, case handling, and key position consistent between sort and join is part of the data contract, not a performance hint.

TERMINALCommand — replaces the lab fixtures
printf '%s\n' \
  'alice:1001:/bin/bash' \
  'bob:1002:/usr/sbin/nologin' \
  'carol:1003:/bin/bash' \
  'dana:1004:/bin/bash' > passwd.snapshot &&
printf '%s\n' 'alice:prod' 'carol:staging' 'erin:prod' > access.snapshot &&
sort -t ':' -k 1,1 passwd.snapshot > passwd.sorted &&
sort -t ':' -k 1,1 access.snapshot > access.sorted

The backslash at the end of each displayed printf line escapes its newline, so Bash continues the same command. No output means the guarded setup and sorts succeeded. These are supplied snapshots, not reads of /etc/passwd or a production authorization system.

03

Choose the delimiter before trusting the fields

The -t option gives join one input and output field separator. Here its argument is a colon. Single quotes preserve the colon as a literal shell argument; the colon has no special meaning to Bash in this position. Because both keys remain field 1, no separate key option is needed.

The output starts with the shared username, then includes the non-key fields from passwd.sorted, followed by the non-key scope field from access.sorted.

TERMINALCommand
join -t ':' passwd.sorted access.sorted
TERMINALOutput
alice:1001:/bin/bash:prod
carol:1003:/bin/bash:staging

This complete-looking report still omits Bob, Dana, and Erin. Successful exit means join processed the ordered inputs; it does not mean every record matched or that either supplied inventory is authoritative. A colon inside a field would also become structure because join is not a CSV or escaping-aware parser.

04

Make missing relationships visible

For a reconciliation report, absence is often the question. The -a 1 option adds unpairable lines from file 1, and -a 2 adds them from file 2. Using both produces the union of keys rather than only the intersection.

The -o option takes an output list. Its quoted argument contains comma-separated field selectors: 0 means the join key from whichever file supplied it; 1.2 and 1.3 mean fields 2 and 3 from file 1; 2.2 means field 2 from file 2. The -e option supplies MISSING for a requested output field that is empty or absent. Without -o, -e has no missing projected field to replace in this example.

These flags describe presentation, not evidence quality. MISSING alone cannot distinguish an unpairable record from a matched input record whose requested field was empty. Use the anti-join in the next section when absence of the key relationship is the question.

TERMINALCommand
join -t ':' -a 1 -a 2 -e MISSING \
  -o '0,1.2,1.3,2.2' passwd.sorted access.sorted
TERMINALOutput
alice:1001:/bin/bash:prod
bob:1002:/usr/sbin/nologin:MISSING
carol:1003:/bin/bash:staging
dana:1004:/bin/bash:MISSING
erin:MISSING:MISSING:prod

Bob and Dana are unpaired in the account snapshot; Erin is unpaired in the access snapshot. The 0 selector matters when unpaired records can come from either file: 1.1 cannot print Erin's key, and 2.1 cannot print Bob's. An empty field or a literal input value equal to MISSING would be indistinguishable from this display, so do not infer absence from the sentinel alone. Choose a sentinel outside the controlled field grammar or use a structured format downstream.

05

Turn an anti-join into a review queue

During an authorized access review, an administrator may want only accounts absent from the supplied approval list. The -v 1 option prints unpairable lines from file 1 instead of printing matches. This is commonly called an anti-join.

The -o list keeps the username, UID, and shell from file 1. Each selector is explicit so a later change to the second file cannot silently add fields to this report.

TERMINALCommand
join -t ':' -v 1 -o '1.1,1.2,1.3' passwd.sorted access.sorted
TERMINALOutput
bob:1002:/usr/sbin/nologin
dana:1004:/bin/bash

Treat these two rows as questions for an owner, not proof of unauthorized access and not authorization to disable an account. A stale or incomplete approval snapshot produces the same absence. Join has compared supplied text; it has not authenticated either source, checked login history, or found a vulnerability.

06

Join different field positions deliberately

A grant inventory may use numeric UID as field 1, while the account snapshot stores UID in field 2. Changing the join field changes the required ordering. Sort passwd.snapshot again on field 2 into passwd.by-uid, and sort the new grants.snapshot on field 1 into grants.by-uid. Both sorts inherit the exported C locale and use the same colon separator as the join.

The -1 2 option selects field 2 from file 1 as its join key. The -2 1 option selects field 1 from file 2. In the output list, 1.1 is the username, 0 is the shared UID, and 2.2 is the grant. The key fields need compatible meanings as well as compatible spelling; join cannot determine that two columns merely happen to contain similar numbers.

TERMINALCommand
printf '%s\n' '1003:audit' '1001:backup' '1004:deploy' > grants.snapshot &&
sort -t ':' -k 2,2 passwd.snapshot > passwd.by-uid &&
sort -t ':' -k 1,1 grants.snapshot > grants.by-uid &&
join -t ':' -1 2 -2 1 -o '1.1,0,2.2' passwd.by-uid grants.by-uid
TERMINALOutput
alice:1001:backup
carol:1003:audit
dana:1004:deploy

Bob has no matching grant and disappears under the default inner-join policy. If this report must show him, add an explicit unpaired-record policy rather than assuming row counts reveal the omission. For POSIX portability, keep the option and its numeric argument separate as shown.

07

Duplicate keys multiply matching pairs

Keys need not be unique. Replace the one-scope access input with multi.sorted, where Alice has two scope records. Join emits one line for every matching pair in the equal-key groups.

The setup remains ordered: both Alice rows are adjacent and precede Carol. The default output repeats the account fields for each matching scope.

TERMINALCommand
printf '%s\n' 'alice:prod' 'alice:staging' 'carol:staging' > multi.sorted &&
join -t ':' passwd.sorted multi.sorted
TERMINALOutput
alice:1001:/bin/bash:prod
alice:1001:/bin/bash:staging
carol:1003:/bin/bash:staging

With two Alice rows in each file, the equal-key group would produce four Alice pairs, not two. That multiplication is legitimate relational behavior, but it can surprise a script that assumes one output row per account. Check or aggregate key cardinality separately when uniqueness is part of the policy; join does not enforce it.

08

Keep a header out of the ordering comparison

A descriptive first line often does not sort with the data beneath it. GNU join's --header option treats the first line of each file as a header, joins those two lines without checking their order, and then processes the remaining data normally.

This option is a GNU extension, not part of the POSIX join interface. The fixture is small enough to show the complete files; the data rows beneath each header remain ordered by username.

TERMINALCommand — GNU extension
printf '%s\n' 'user:uid:shell' 'alice:1001:/bin/bash' 'bob:1002:/usr/sbin/nologin' > users.header &&
printf '%s\n' 'user:scope' 'alice:prod' 'bob:dev' > scopes.header &&
join -t ':' --header users.header scopes.header
TERMINALOutput
user:uid:shell:scope
alice:1001:/bin/bash:prod
bob:1002:/usr/sbin/nologin:dev

Header recognition is positional: the first line is special because --header says so, not because its key is named user. On implementations without this extension, remove and restore headers explicitly with reviewed tooling, or keep metadata outside the data stream.

09

Fail closed when ordering is uncertain

GNU join normally diagnoses some disorder, but it is not a general sortedness validator: without an explicit check, disorder is guaranteed to be reported only when it leads to unpairable input. For an audit pipeline, request the stronger contract.

Create unsorted with carol before alice. The exported C locale keeps the comparison rule deterministic. The GNU --check-order option requires every input to be correctly ordered even if all lines might otherwise pair. The command writes its ordinary output to unsorted.out and its diagnostic to unsorted.err; those redirections let the shell inspect each channel separately.

The following command is expected to fail. The || operator runs its right side only after a nonzero status. printf then reports that status. This demonstration does not feed the incomplete output into another decision.

TERMINALCommand — expected failure
printf '%s\n' 'carol:staging' 'alice:prod' > unsorted &&
join --check-order -t ':' passwd.sorted unsorted \
  > unsorted.out 2> unsorted.err ||
printf 'join rejected unsorted input: status=%s\n' "$?" &&
cat unsorted.err
TERMINALOutput and standard-error text on GNU Coreutils 9.7
join rejected unsorted input: status=1
join: unsorted:2: is not sorted: alice:prod

The shell's $? expands to join's status because it is the command immediately before ||. The final cat displays the saved diagnostic. Diagnostic wording can change across versions and locales; the nonzero status and rejected input are the contract. --check-order is GNU-specific. A portable workflow can validate ordering with a separately specified check before invoking join.

10

Change the outer record boundary without changing fields

A newline-delimited record cannot safely contain a newline. GNU -z changes join's input and output record terminator to NUL, the zero byte that Unix pathnames cannot contain. This is useful for controlled pathname-derived inventories, but it does not make colon safe inside a field.

The first printf creates two NUL-terminated left records. Alice's second field contains an embedded newline. The second creates matching right records. In printf's format, \000 denotes NUL; the shell's single quotes preserve the escapes for printf. Join receives ordinary files, uses colon as the inner field separator, and emits NUL-terminated combined records.

Because terminal display cannot make NUL boundaries reliable, the pipe sends join's standard output to od for a byte rendering. The od article explains this representation: -A n uses n as the address-radix argument and suppresses address offsets, while -t x1 uses x1 as its format argument and prints one-byte hexadecimal values.

TERMINALCommand — GNU extension
printf 'alice:note line 1\nline 2\000bob:plain\000' > left.nul &&
printf 'alice:prod\000bob:dev\000' > right.nul &&
join -z -t ':' left.nul right.nul | od -A n -t x1
TERMINALOutput bytes
 61 6c 69 63 65 3a 6e 6f 74 65 20 6c 69 6e 65 20
 31 0a 6c 69 6e 65 20 32 3a 70 72 6f 64 00 62 6f
 62 3a 70 6c 61 69 6e 3a 64 65 76 00

Byte 0a is Alice's embedded newline; byte 00 ends each joined record. The colon byte 3a still separates fields, so arbitrary fields containing colons remain ambiguous. Every producer and consumer must preserve the NUL framing. Do not store this stream in a shell variable, because shell variables cannot contain NUL.

11

State the contract before reading the report

Join is dependable when you can answer four questions: which field is the identity, how are fields and records delimited, what exact comparison and ordering produced the inputs, and what should happen to unmatched or duplicate keys? Make those choices in the command and in the collection process.

The command's unusual power is not hidden syntax. It is the ability to express intersection, union, difference, and one-to-many relationships as a streaming text merge. The corresponding danger is also ordinary: a stale inventory, incompatible sort, ambiguous delimiter, or false uniqueness assumption can make polished output misleading. Preserve provenance, check completion and cardinality, and treat reconciliation rows as evidence to investigate rather than decisions made by the tool.

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…