Linux Command Reference ยท Text Processing
Linux tsort command
Reference for the Linux tsort command: order items by dependency pairs, detect cycles, and use it to plan build or install order in shell scripts.
tsort performs a topological sort. You feed it pairs of words, each meaning "the first must come before the second", and it prints every word once in an order that respects all the pairs. It is the classic tool for dependency problems: build order, installation order, course prerequisites.
Input is read as a stream of whitespace-separated tokens, taken two at a time. Writing a b says a comes before b. A pair of identical words, x x, just declares that x exists with no ordering requirement.
tsort [FILE]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
tsort [OPTION] [FILE]
| Name | Description |
|---|---|
FILE |
File with the pairs; standard input if omitted or -. |
--help, --version |
Standard GNU options. |
Returns: 0 on success; 1 if the input has a cycle or an odd number of tokens.
Errors: a cycle prints tsort: FILE: input contains a loop: followed by the nodes involved, but the other nodes are still printed in some order. An odd token count prints input contains an odd number of tokens.
Usage notes
- The result is one valid order, not the only one. When several items are independent, GNU
tsortpicks an order that is deterministic for a given input but not guaranteed to be the same in other implementations. - Direction matters.
A Bmeans A first. If your data reads "A depends on B", swap the columns (awk '{print $2, $1}') before sorting. - Cycles are reported, not fixed. The message lists the nodes on a loop; remove one edge and run again.
- Token based, not line based. Layout is irrelevant:
a b c dmeans the pairsa bandc d. - Self-pairs declare items. Use
item itemfor things that have no dependency edges but must appear in the output. - Names are plain strings, compared byte for byte. Spaces in names are not supported.
- Typical uses: ordering object files for a static library (the original reason for the tool), sorting packages by dependency, checking a Makefile-like graph for loops.
- Not a numeric or alphabetical sorter. For that use
sort.
Related
sort,uniq,awk,comm- Lessons: Sort, uniq and cut, Text Pipelines