How to Use sort Command in Bash: Syntax and Examples
In bash, use the
sort command to arrange lines of text or file contents in order. You can sort alphabetically or numerically by running sort filename or piping text to sort. Options like -r reverse the order and -n sorts numerically.Syntax
The basic syntax of the sort command is:
sort [options] [file]
Where:
optionsmodify how sorting is done (e.g., numeric, reverse).fileis the name of the file to sort. If omitted,sortreads from standard input.
bash
sort [options] [file]
Example
This example shows how to sort a list of words alphabetically and then numerically with reverse order.
bash
echo -e "banana\napple\ncherry" | sort echo -e "10\n2\n30" | sort -n -r
Output
apple
banana
cherry
30
10
2
Common Pitfalls
Common mistakes include:
- Not using
-nfor numeric sorting, which causes numbers to sort as text (e.g., "10" before "2"). - Forgetting that
sortreads from standard input if no file is given. - Not using
-rto reverse order when needed.
bash
echo -e "10\n2" | sort # Output sorts as text, not numbers echo -e "10\n2" | sort -n # Correct numeric sort
Output
10
2
2
10
Quick Reference
| Option | Description |
|---|---|
| -n | Sort numerically |
| -r | Reverse the sort order |
| -k | Sort by a specific column or field |
| -u | Output only unique lines |
| -t | Specify a delimiter for fields |
Key Takeaways
Use
sort filename to sort file contents alphabetically by default.Add
-n to sort numbers correctly instead of as text.Use
-r to reverse the sorting order.If no file is given,
sort reads from standard input.Combine options like
-k and -t to sort by specific columns.