sort Command in Linux: Sort Lines of Text and Numerical Data
Learn sort command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn sort command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What sort Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Mastering the sort command in linux is essential for organizing, analyzing, and transforming structured text data across command-line environments. Standardized in POSIX and provided by GNU coreutils, sort reorganizes lines of text according to user-defined collation rules, handling everything from basic ASCII alphabetical ordering to complex multi-column numerical comparisons.
The sort command in Linux sorts lines of text files or standard input in lexicographical, numerical, or custom order, writing the sorted stream to standard output. Run sort file.txt for alphabetical sorting, sort -n numbers.txt for numerical ordering, sort -k2,2 -t: /etc/passwd to sort by a specific column, or sort -u to deduplicate lines.
In Unix pipelines, sort frequently serves as the indispensable bridge between data generation and data aggregation. Utilities like uniq require sorted input to eliminate duplicate records, while reporting tools rely on sort to rank top-consuming processes, identify disk-heavy directories, and surface anomalous web traffic.
Beyond simple text ordering, GNU sort incorporates advanced sorting modes: human-readable numbers (-h, e.g. 2K, 4M, 1G), version numbers (-V), month names (-M), random shuffling (-R), and external merge sort capabilities that process multi-gigabyte datasets without exhausting system memory.
What sort Does and When to Use It
At the architectural level, GNU coreutils sort uses an external merge sort algorithm. When sorting small datasets that fit into memory, sort utilizes an in-memory quicksort or introsort routine. However, when processing massive datasets that exceed the memory allocation threshold specified by -S (--buffer-size), sort partitions the input into temporary sorted chunks, writes them to temporary spill files in /tmp (or the path defined by -T), and merges the sorted runs using a k-way tournament tree.
Collation rules are heavily influenced by the active system locale: by default, sort honors the LC_COLLATE and LC_ALL environment variables. In UTF-8 locales (such as en_US.UTF-8), collation rules follow complex dictionary ordering that ignores certain punctuation and case differences. For deterministic, high-speed, byte-level ASCII sorting in shell scripts, administrators set LC_ALL=C, which bypasses locale lookup tables and boosts sort speed by 2x to 5x.
Under the hood, sort gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -n, -r, -u, -k POS1[,POS2] turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The sort utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:
Before running administrative tasks or automation scripts, verify whether sort is installed and inspect which binary path and version your shell resolves:
type -a sort
sort --version 2>/dev/null || man -f sort
# Illustrative output (reviewed against documentation)
sort is /usr/bin/sort
sort (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils
# Arch Linux
sudo pacman -S --noconfirm coreutils
# Alpine Linux
sudo apk add --no-cache coreutils
Command Syntax, Arguments, and Exit Status Codes
sort [OPTION]... [FILE]...
The syntax follows the structure sort [OPTION]... [FILE].... If multiple files are passed, sort reads and merges all of them into a single sorted output stream. If no FILE arguments are given or a hyphen (-) is supplied, sort reads from standard input (stdin).
Sorting keys are defined using the -k POSIX syntax: -k POS1[,POS2], where POS1 is the starting field and character offset, and POS2 is the optional ending field. The field delimiter is defined with -t (defaulting to transitions between non-whitespace and whitespace).
0— Successful execution; input successfully sorted and emitted.1— Operational failure; file unreadable, or when -c is used, input was not sorted.2— Command-line syntax error or invalid key specification.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-n | --numeric-sort | Compare according to string numerical value (handles negative numbers and decimals). |
-r | --reverse | Reverse the result of comparisons (descending order). |
-u | --unique | Output only the first of an equal run (deduplicates sorted lines). |
-k POS1[,POS2] | --key=POS1[,POS2] | Sort by a key defined by column positions POS1 through POS2. |
-t SEP | --field-separator=SEP | Use character SEP as the field delimiter instead of whitespace. |
-h | --human-numeric-sort | Compare human-readable numbers (e.g. 2K, 45M, 2G). |
-V | --version-sort | Natural sort of version numbers within text (e.g. v1.2, v1.10). |
-c | --check | Check whether input is already sorted; do not sort if ordered. |
-S SIZE | --buffer-size=SIZE | Set the maximum main memory buffer size (e.g. -S 2G). |
A common trap in Linux administration is sorting numerical data without -n. In standard lexicographical sorting, '10' appears BEFORE '2' because the character '1' precedes '2' in the ASCII table. Passing -n guarantees proper mathematical comparison.
When sorting specific columns, always restrict the key range explicitly using -k 2,2 rather than -k 2. An open-ended key like -k 2 instructs sort to compare starting from column 2 all the way to the end of the line, which can distort results if trailing columns vary.
When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.
Practical Basic and Advanced Usage Examples
1. Basic Alphabetical Sorting of Text Lines
Sort a list of server hostnames alphabetically in ascending order.
cat << 'EOF' > hosts.txt
web-02
db-01
api-01
web-01
EOF
sort hosts.txt
# Illustrative output (reviewed against documentation)
api-01
db-01
web-01
web-02
sort orders lines alphabetically based on standard ASCII/locale collation.
2. Sort Numbers Mathematically with -n and Reverse Order with -r
Sort a list of process IDs or numeric port numbers in descending mathematical order.
printf "100\n2\n50\n1\n25\n" | sort -nr
# Illustrative output (reviewed against documentation)
100
50
25
2
1
The -n flag ensures 100 is evaluated as greater than 50, and -r reverses output into descending order.
3. Sort by Specific Column Using -t and -k
Sort /etc/passwd numerically by the third column (UID).
sort -t: -k3,3n /etc/passwd | head -n 4
# Illustrative output (reviewed against documentation)
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
Setting -t: defines the colon delimiter, and -k3,3n restricts numerical sorting strictly to field 3.
4. Sort Human-Readable Storage Sizes with -h
Sort directory disk usage outputs from du -h in human-readable order (KB, MB, GB).
printf "1.2G\n450M\n2.5G\n12K\n" | sort -h
# Illustrative output (reviewed against documentation)
12K
450M
1.2G
2.5G
The -h flag parses metric and binary multipliers (K, M, G, T) to sort human-readable units accurately.
5. Sort Software Release Version Strings with -V
Sort application version tags naturally so version 1.10 appears after version 1.9.
printf "v1.9.0\nv1.10.0\nv1.2.1\nv1.20.0\n" | sort -V
# Illustrative output (reviewed against documentation)
v1.2.1
v1.9.0
v1.10.0
v1.20.0
The -V flag enables version sorting, treating multi-digit numbers within strings as numbers rather than characters.
6. Deduplicate Lines While Sorting Using -u
Sort an unsorted list of IP addresses and eliminate duplicate entries in a single step.
printf "192.168.1.1\n10.0.0.1\n192.168.1.1\n172.16.0.1\n" | sort -u
# Illustrative output (reviewed against documentation)
10.0.0.1
172.16.0.1
192.168.1.1
The -u flag suppresses duplicate keys, producing a sorted, unique list identical to piping into uniq.
Real-World Workflows, Pipelines, and Shell Automation
Disk Capacity Audit: Finding Largest Directories in /var
Identify the top 5 largest directories consuming storage space using du and sort.
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="/var/log"
echo "=== Top 5 Storage Consumers in $TARGET_DIR ==="
sudo du -h --max-depth=1 "$TARGET_DIR" 2>/dev/null \
| sort -hr \
| head -n 6
# Illustrative output (reviewed against documentation)
=== Top 5 Storage Consumers in /var/log ===
4.2G /var/log
2.8G /var/log/journal
850M /var/log/nginx
320M /var/log/audit
110M /var/log/apt
du generates human-readable disk sizes, and sort -hr orders them from largest to smallest, highlighting storage bottlenecks.
Web Server Analytics: Identifying Top 5 Remote Client IP Addresses
Parse an Nginx access log to aggregate and order the most active visitors by request volume.
#!/usr/bin/env bash
set -euo pipefail
LOG="/var/log/nginx/access.log"
echo "=== Top 5 Active Client IP Addresses ==="
awk '{print $1}' "$LOG" \
| sort \
| uniq -c \
| sort -nr \
| head -n 5 \
| while read -r count ip; do
printf "%6d requests from %s\n" "$count" "$ip"
done
# Illustrative output (reviewed against documentation)
=== Top 5 Active Client IP Addresses ===
1842 requests from 198.51.100.44
940 requests from 203.0.113.12
812 requests from 192.0.2.89
310 requests from 198.51.100.12
115 requests from 203.0.113.88
This classic pipeline uses sort to group identical IPs for uniq -c, followed by sort -nr to rank attackers or crawlers.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding sort inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.
Permissions, Security Implications, and Safe Execution
Never attempt to sort a file in place using shell redirection into itself (e.g. sort file.txt > file.txt). The shell truncates file.txt to 0 bytes before sort opens it. Always use GNU sort's built-in output flag -o file.txt (e.g. sort -o file.txt file.txt).
When sorting large files from untrusted sources, be mindful of temporary disk usage. By default, sort spills temporary merge runs into /tmp. If an attacker feeds an unconstrained multi-gigabyte dataset, /tmp may fill up, causing other system daemons to fail. Use -T to redirect temporary files to a dedicated scratch partition.
In shell scripts comparing cryptographic hashes or deterministic tokens, always enforce LC_ALL=C. Locale-dependent sorting can alter character ordering across different server environments, leading to subtle verification discrepancies.
GNU/Linux, BSD, and BusyBox Implementation Differences
The options -n, -r, -u, -k, and -t are strictly standardized in POSIX.1 and function identically across GNU, BSD, and BusyBox implementations.
The -h (--human-numeric-sort) and -V (--version-sort) options are GNU coreutils extensions. On BSD platforms (macOS, FreeBSD) or minimal BusyBox systems (Alpine Linux), sort -h and sort -V may be unsupported. For portable scripts, convert sizes to raw byte integers before sorting.
Troubleshooting Common Errors and Diagnostics
Numbers sorting out of order (e.g. 10 appears before 2)
Root Cause: sort was executed without the -n (--numeric-sort) flag, resulting in lexicographical ASCII comparison where '1' comes before '2'.
Resolution: Add the -n flag for numerical sorting.
sort -n numbers.txt
sort: /tmp/sortXXXXXX: No space left on device
Root Cause: The dataset being sorted exceeds available free space in the default /tmp filesystem partition during external merge sorting.
Resolution: Specify an alternate temporary directory with ample storage using -T.
sort -T /var/scratch/ -S 4G large_data.csv
Inconsistent sort ordering between local machine and server
Root Cause: The two systems have different locale configurations (e.g. en_US.UTF-8 vs C.UTF-8), altering collation weight rules for punctuation and capitalization.
Resolution: Prefix sort with LC_ALL=C to enforce standard byte-order collation.
LC_ALL=C sort file.txt
Alternatives, Related Commands, and Related Tutorials
- awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - tr Command in Linux: Translate, Delete, and Squeeze Characters — Practical syntax, flags, and examples for
tr. - Cut Command in Linux: Extract Columns, Fields, and Characters — Practical syntax, flags, and examples for
cut. - uniq Command in Linux: Filter and Count Duplicate Text Lines — Practical syntax, flags, and examples for
uniq. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!