Start with three destinations
Comm compares two sorted inputs and sends each line to one of three output columns: only in the first input, only in the second, or present in both. It is a standalone utility, not a shell built-in. Reach for it when the question is membership: which expected configuration entries are missing, which observed entries are new, and which are shared? It compares whole records, not a selected field or the position a line occupied before sorting.
Begin with synthetic service names. The expected inventory is auditd, cron, sshd; the observed inventory is auditd, nginx, sshd. Each name occupies its own newline-terminated line, and both lists are already sorted. In the final command below, expected.txt is the first input and observed.txt is the second. Standard output is the normal result stream, shown in the terminal here.
Run the examples in order in one Bash session. They were tested with GNU Coreutils 9.4 and Bash 5.2.21 on Linux. The basic three-column operation and -1, -2, and -3 are specified by POSIX; later GNU extensions are identified explicitly. Other implementations need their own option checks.
The setup creates a disposable comm-lab directory and two files. If that directory already exists, choose a new name and rerun setup; do not continue after a failed setup. The shell's && runs the next command only if the previous one succeeds. Mkdir creates the directory, cd enters it, and > creates or replaces a file. Printf's %s prints each following string, and \n adds its newline; single quotes preserve the format for printf. Export LC_ALL=C selects the C locale for this shell and its child commands, giving these examples consistent byte-based ordering rather than language-dependent collation. Use this dedicated session for the lab; the locale setting remains until changed or the session ends.
export LC_ALL=C &&
mkdir comm-lab &&
cd comm-lab &&
printf '%s\n' auditd cron sshd > expected.txt &&
printf '%s\n' auditd nginx sshd > observed.txt &&
comm expected.txt observed.txt auditd
cron
nginx
sshdThere is no header row. With all columns enabled, zero leading tabs means first-input-only, one means second-input-only, and two means shared. Thus cron is missing from the observation, nginx is additional, and auditd and sshd are shared. This interpretation assumes the input records do not themselves begin with tabs. Comm does not label records or escape their contents.
Suppress the answers you do not need
The numbers name columns to suppress, not columns to select. The -1 flag hides first-input-only records; -2 hides second-input-only records; -3 hides shared records. To get only missing names, suppress columns two and three with -2 -3. The compact spelling -23 means the same thing.
The next three commands ask, in order, for missing, added, and shared names. In -13, the two combined flags hide columns one and three; in -12, they hide columns one and two. The inputs stay unchanged.
comm -2 -3 expected.txt observed.txt
comm -13 expected.txt observed.txt
comm -12 expected.txt observed.txtcron
nginx
auditd
sshdEach command leaves one column, so no leading column separators remain. Cron belongs to the first command, nginx to the second, and the final two lines to the third. Reversing the input filenames reverses the meaning of “missing” and “added”; the shared records stay shared.
Sort the same records by the same rules
Comm's useful mental model is a merge of two ordered streams. If the next records match, it pairs them and advances both inputs. Otherwise, it emits the earlier record and advances that input. It can move forward because correctly sorted inputs cannot hide an earlier record farther down the stream. Unsorted input breaks that reasoning; comm does not sort for you.
The sort deep dive explains the underlying ordering choices. The refresher needed here is short: plain sort orders complete lines; sort -u additionally retains one representative of each group of equal lines. With C ordering and no key or numeric options, that gives one copy of each distinct line. Both sorts and comm must use the same locale. The exported LC_ALL=C already covers all three commands; setting it for comm alone would not repair files sorted under different rules.
Create two raw inventories with shuffled records; expected.raw also contains sshd twice. This example deliberately asks about membership, not frequency, so it writes deduplicated copies into expected.set and observed.set. Those suffixes are descriptive names, not special file formats. The originals are preserved. The && chain prevents comparison if either write or sort fails.
printf '%s\n' sshd auditd cron sshd > expected.raw &&
printf '%s\n' sshd nginx auditd > observed.raw &&
sort -u expected.raw > expected.set &&
sort -u observed.raw > observed.set &&
comm -13 expected.set observed.setnginx“Sorted” must mean the order comm expects, not merely some order. Numeric, reverse, case-folded, or selected-field sorting can violate full-record comparison order. For example, numeric ordering puts 2 before 10, whereas C full-line ordering puts 10 before 2. Use the same plain full-record ordering throughout this workflow. Deduplication and any earlier normalization are policy decisions; they do not make an inventory complete or trustworthy.
A duplicate is another occurrence
Comm does not automatically convert its inputs into mathematical sets. To see why that matters, sort the raw files again without -u. These new counted files retain the repeated sshd. The first comparison asks for expected occurrences not paired with an observed occurrence; the second asks for paired occurrences.
sort expected.raw > expected.counted &&
sort observed.raw > observed.counted &&
comm -23 expected.counted observed.counted &&
comm -12 expected.counted observed.countedcron
sshd
auditd
sshdThe first command emits cron and one excess sshd; the second emits auditd and the paired sshd. An sshd in the first result does not mean sshd is wholly absent from the observed inventory. In these GNU 9.4 tests, repeated equal lines pair one occurrence at a time: two copies against one produce one shared copy and one left-only copy. This is multiset-like comparison, where multiplicity matters. Keep duplicates for occurrence reconciliation; use sort -u on both sides only when membership is the intended question.
Reject an ordering failure, including partial output
GNU comm's --check-order flag makes incorrectly ordered input an error. GNU's default check is weaker: the manual says it diagnoses disorder only when it encounters unpairable lines. Two identical but unsorted files can therefore appear to compare successfully by default. An empty difference is not an ordering check.
Create disorder.txt with sshd before auditd, the reverse of their C order. This command deliberately fails. The shell's if runs its condition and takes the then branch on status zero or the else branch on nonzero status; fi closes the conditional. The semicolon separates the condition command from then on the same line. The > redirection captures normal output in rejected.txt, while 2> captures the diagnostic stream, standard error, in order-error.txt. Both files are created or replaced before comm runs.
In the failure branch, status=$? immediately saves the previous command's exit status. The later "$status" expands that saved value as one argument; printf inserts it into %s. Cat copies the diagnostic file to the terminal. We never print or consume rejected.txt as comparison data.
printf '%s\n' sshd auditd > disorder.txt &&
if comm --check-order disorder.txt disorder.txt > rejected.txt 2> order-error.txt; then
printf '%s\n' 'comparison unexpectedly succeeded'
else
status=$?
printf 'rejected comparison: status %s\n' "$status"
cat order-error.txt
firejected comparison: status 1
comm: file 1 is not in sorted orderA comparison can emit records before detecting disorder. Reject its entire result on failure, not just the last line. GNU --nocheck-order disables order checking; it does not sort, repair, or give meaningful guarantees for wrongly ordered inputs. The GNU manual explicitly warns against relying on such results. Neither long flag belongs to the POSIX comm interface.
Successful comparison is not equality
Unlike a difference-reporting exit status, comm's status tells you whether processing succeeded. POSIX specifies zero for successful processing and a positive status for an error; GNU follows that distinction. Differing inputs normally still return zero.
Here the second command prints $? immediately, so it reports comm's status rather than that of a later helper. The double quotes keep the expanded status as one shell argument.
comm -13 expected.txt observed.txt
printf 'comm status: %s\n' "$?"nginx
comm status: 0There are two separate questions: did comparison succeed, and did the selected result contain records? Testing only the exit status answers the first. Even a successful empty result answers only the selected question: no additions does not imply no removals.
Gate the report before investigating drift
For an administrative check, first establish that the comparison succeeded, then inspect the report. This example creates or replaces additions.txt inside the lab. GNU --check-order validates the order while -13 selects only observed names absent from the expected list.
Inside the success branch, [ -s additions.txt ] is the shell's file test: it succeeds when that file exists and has nonzero size. Spaces around the brackets and arguments are required. The nested if distinguishes a nonempty report from an empty one. The outer failure branch does not read the report at all. It prints a warning to standard error using >&2, which redirects printf's normal output to that diagnostic stream.
if comm --check-order -13 expected.set observed.set > additions.txt; then
if [ -s additions.txt ]; then
printf '%s\n' 'Review added names:'
cat additions.txt
else
printf '%s\n' 'No added names.'
fi
else
printf '%s\n' 'Comparison failed; discard additions.txt.' >&2
fiReview added names:
nginxApply this pattern to authorized configuration or account-inventory review, not automatic deletion. A new name can reflect an approved deployment, different collection scope, stale data, or an unauthorized change. The difference itself is not proof of compromise. Record how and when each inventory was collected, use a trusted baseline, and investigate against the change record. This demonstration reports outcomes; a production script should additionally propagate a nonzero failure status to its caller.
Make the column markers visible
GNU --output-delimiter takes a string to place between output columns instead of a tab. The equals sign attaches its argument; single quotes preserve the spaces and literal vertical bar, preventing the shell from treating that bar as a pipeline operator. This changes presentation, not the comparison or record separator.
comm --output-delimiter=' | ' expected.txt observed.txt | | auditd
cron
| nginx
| | sshdShared lines have two markers, second-input-only lines one, and first-input-only lines none. This is not a padded spreadsheet or an escaping format: records containing your delimiter remain ambiguous. For downstream processing, select one column instead of trying to reconstruct classification from decorative separators. --output-delimiter is a GNU extension, not a POSIX option.
Generated streams save staging, not error handling
Bash process substitution lets comm read generated output through filename-like arguments. In <(sort -u expected.raw), Bash starts sort asynchronously and supplies a readable path connected to its output. The < and ( must touch. The second substitution independently prepares the observed stream. Both inherit the exported C locale, and comm compares their sorted output without creating our own intermediate .set files.
This syntax is a Bash feature, not POSIX shell syntax. The GNU Bash manual describes the implementation using named pipes or /dev/fd where supported; a script must choose a compatible shell and environment.
comm -13 <(sort -u expected.raw) <(sort -u observed.raw)nginxThe short form hides an important boundary: comm's success does not collect the asynchronous sort commands' exit statuses. A failed producer can supply an empty or incomplete stream that comm accepts. For an auditable reconciliation, prefer the earlier staged sort commands joined by &&, retain the original inputs, and consume comparison output only after success. Process substitution is convenient for known-good inputs, not a replacement for checking producers.
Preserve pathname records that contain newlines
A newline-delimited inventory cannot represent every Unix pathname unambiguously: a pathname can itself contain a newline. NUL, a byte with value zero, cannot occur inside a Unix pathname, so NUL termination can preserve the boundary between pathname records. GNU sort -z and GNU comm -z both change their input and output record terminator from newline to NUL. They must agree on that contract; changing only the last command cannot recover boundaries already lost upstream.
Create synthetic pathname lists, not actual configuration files. In printf's quoted format, \0 emits a NUL byte and \n emits a newline. The expected list contains etc/sshd; the observed list adds one pathname whose bytes spell etc/new, a newline, then name. Sort -z -u orders and deduplicates those whole NUL-terminated records. Comm -z -13 retains only added pathname records and writes them to added.paths. Every write and transform is guarded by &&.
Od displays bytes rather than sending the embedded newline and NUL to the terminal. Its -A n suppresses address labels, -t x1 selects one-byte hexadecimal units, and -v prevents repeated rows from being replaced by an abbreviation. These options affect the display only.
printf 'etc/sshd\0' > expected.paths.raw &&
printf 'etc/sshd\0etc/new\nname\0' > observed.paths.raw &&
sort -z -u expected.paths.raw > expected.paths &&
sort -z -u observed.paths.raw > observed.paths &&
comm -z -13 expected.paths observed.paths > added.paths &&
od -A n -t x1 -v added.paths 65 74 63 2f 6e 65 77 0a 6e 61 6d 65 00The 0a byte is the newline inside the one added pathname; 00 ends that record. The xargs deep dive explains producing pathname records with find -print0, which terminates each emitted path with NUL. A real workflow must preserve that format through every stage. GNU comm -z preserves record boundaries; it does not validate paths, establish that they exist, or make later filesystem operations safe. Do not infer -z support from a utility's name on another implementation.
Decide what a record means before comparing it
For configuration inventories, comparing whole lines can be precisely right. For account inventories, it can be wrong if the intended identity is just the account name while the line also contains changing metadata. Choose and document the identity fields before preparing both inputs, and preserve the source exports separately. Comm has no key-selection option and does not join related fields for you.
Likewise, a record comparison is not an exact-byte integrity check. GNU comm silently supplies a missing final newline, and sorting discards original order. The fixtures here are deliberately terminated and synthetic. Keep original artifacts when their ordering, terminators, or collection provenance matter.
The useful decision sequence is small: define a record, decide whether duplicate occurrences count, order both inputs under the same rules, check every producer and comparison, then interpret the selected records in operational context. Comm does the middle comparison well. It cannot decide whether the inventories asked the right question.