How does the sort command work in the context of the given command?

QuestionsQuestions8 SkillsProDec, 19 2025
0119

In the context of the command:
find . -type f -exec du -h {} + | sort -hr | head -n 5

The sort command is the "brain" that organizes the list of files provided by du. Here is exactly what those specific flags do:

1. The -h (Human-Numeric Sort)

This is the most important flag for this specific task.

  • The Problem: Normal sorting treats text literally. Alphabetically, "10K" comes before "20", and "2G" comes before "5M" because of the letters.
  • The Solution: The -h flag tells sort to understand human-readable suffixes (K, M, G). It knows that 10M is larger than 500K, even though "5" is larger than "1".

2. The -r (Reverse)

  • By default, sort goes from smallest to largest (ascending).
  • Since we are usually looking for the biggest files taking up space, -r reverses the order so the largest files appear at the very top of the list.

3. The Pipe |

  • The sort command doesn't know about files on its own. It receives the text output from the du command via the pipe (|).
  • du says: "Here is a list of files and their sizes."
  • sort says: "Okay, I'll rearrange this list by the numbers and units I see at the start of each line."

Why it’s used here:

Without sort -hr, the output would be in random order (based on how find walked through your folders). By adding it, you turn a messy list into a "Top Space Consumers" leaderboard. This makes it easy for the head -n 5 command to grab just the 5 biggest ones.

0 Comments

no data
Be the first to share your comment!