0
0
Bash-scriptingHow-ToBeginner · 3 min read

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:

  • options modify how sorting is done (e.g., numeric, reverse).
  • file is the name of the file to sort. If omitted, sort reads 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 -n for numeric sorting, which causes numbers to sort as text (e.g., "10" before "2").
  • Forgetting that sort reads from standard input if no file is given.
  • Not using -r to 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

OptionDescription
-nSort numerically
-rReverse the sort order
-kSort by a specific column or field
-uOutput only unique lines
-tSpecify 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.