Overview
sort reads lines from files or standard input and prints them in order. By default it compares text using the current locale, so punctuation, case, and numbers sort as text.
Background
A sort command first appeared in Version 1 Unix, according to the FreeBSD and macOS manuals. Today the name covers GNU sort, the sort that macOS ships, and the sort applet in BusyBox. They agree on -r, -n, -u, -t, and -k, and differ on options such as -h and -V.
Examples
Sort lines alphabetically:
sort fruit.txt
Sort in reverse order:
sort -r fruit.txt
Sort numbers by value instead of as text:
sort -n nums.txt
Sort and drop duplicate lines:
sort -u fruit.txt
Sort a comma-separated file by its second column; the header sorts first because it has no number:
sort -t, -k2,2n data.csv
Find the largest number:
sort -rn nums.txt | head -n 1
Options
-r
Reverse the order.
-n
Compare as numbers, not text. Without it, 10 sorts before 9.
-u
Output only the first of lines that compare equal, which also removes duplicates.
-t
Set the field separator for -k to this single character, as in -t,.
-k
Sort by a field or character range. -k2,2n means start and stop at field 2, numerically; without the
,2 the key runs to the end of the line.
Common mistakes
Without -n, numbers sort as text, so 10 comes before 9. Order depends on the locale: the examples here use the C locale (LC_ALL=C) for predictable results, and other locales can sort case and punctuation differently. sort file > file empties the file before sorting; write to another file.
Portability
-r, -n, -u, -t, and -k are in the Common examples. The Common examples were executed on GNU coreutils 9.11, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check). Version sort -V, human-numeric -h, and stability options differ between builds.
About macOS sort
This is the sort in /usr/bin on macOS. Its --version output reads 2.3-Apple, which is why implementation detection checks for Apple before GNU.
Apple notes
macOS sort identifies itself as 2.3-Apple and is derived from GNU sort, so most common options match; confirm rarely used long options before relying on them.
References
Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.