TSORT(1) General Commands Manual TSORT(1)

tsortstable total ordering

tsort [file]

Constructs a directed graph from the pairs of whitespace-separated node relationships provided in file (standard input stream if "-", the default), then writes all unique nodes to the standard output stream, one per line, sorted according to the total ordering described by that graph, consistently with the partial ordering of the final occurrence of nodes in the input.

An input pair in the form "a a" indicates presence of node a. An input pair in the form "a b" indicates an a → b relationship: a sorts earlier than b; this is transitive: another "b c" node means that a → b → c, i.e. a sorts earlier than b sorts earlier than c (indeed, a node sorts earlier than a different node if the latter can be reached from the former).

Edges that would cause a cycle are removed, as they can interfere with preserving the input's partial ordering.

if file (the standard input stream) couldn't be read, or contained an odd amount of tokens.

The simple case

$ cat nodes
A B
A F
B C
B D
D E
$ tsort nodes
A
F
B
C
D
E
Corresponds to this graph:
A → F
↓
B → C
↓
D
↓
E

By adding a D → A relationship, an A → B → D → A loop is created:

$ echo A B A F B C B D D E D A | tsort
tsort: -: breaking D -> A link
A
F
B
C
D
E
Corresponding to this graph:
A → F
↑ ↓
| B → C
| ↓
|←D
  ↓
  E
But, as the the looping D → A link is removed, it resolves to the same graph as the previous example.

This input:

$ tsort
a b c c d e
g g
f g e f
h h
^D
a
b
c
d
e
f
g
h
Corresponds to this graph:
a  c  d  h
↓     ↓
b     e
      ↓
      f
      ↓
      g

lorder(1)

Conforms to IEEE Std 1003.1-2008 (“POSIX.1”).

Appeared in Version 7 AT&T UNIX, fully formed, as

tsort - topological sort
pointing at lorder(1), which notes:
This brash one-liner intends to build a new library from existing '.o' files.
ar cr library `lorder *.o | tsort`

X/Open Portability Guide Issue 2 (“XPG2”) includes it verbatim.

June 8, 2023 voreutils pre-v0.0.0-latest