← All commands
THE COMMAND REFERENCE

tsort

Sort items so that each comes after the items it depends on.

Last updated

Portable / common

Implementation-level reference; examples are not certified for every installed version.

Overview

tsort does a topological sort: it reads pairs of names, each meaning "the first must come before the second", and prints the names in an order that respects every pair. It is useful for dependencies, such as which package to build first. A loop in the pairs, where A needs B and B needs A, has no valid order.

Background

The tsort command appeared in Version 7 AT&T UNIX, according to the macOS manual. Today the name covers GNU tsort and the tsort that macOS ships. The BusyBox 1.37.0 build used for this page has no tsort applet. They agree on reading pairs of names and printing an order.

Examples

Order three names from two pairs:

printf 'a b\nb c\n' | tsort

Give more pairs, including two that start from the same name; any order that respects every pair is valid, so only one is shown here:

printf 'a b\na c\n' | tsort | head -n 1

A name on its own as a pair of the same name keeps it in the output, with no ordering constraint:

printf 'a a\nb c\n' | tsort | sort | paste -sd, -

Common mistakes

The order is not unique when several names are independent, so two implementations can print different valid orders for the same input. A loop in the pairs is an error on GNU, with a message and a non-zero exit status, and on macOS the check printed a warning and still produced output, so do not rely on one behavior. Names are separated by blanks, so a name with a space needs a different tool.

Portability

This page has no BusyBox view: BusyBox has no tsort applet. The Common examples avoid loops and unspecified orders. The Common examples were executed on GNU coreutils 9.11 and macOS system tools (see the development guide for the exact check).

References

Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.