How can I sort du -h output by size in Linux

When dealing with disk usage (du) in Linux, it’s often helpful to sort the output by size to quickly identify the largest directories. Follow these steps to accomplish this:

Run the du -h Command:

  1. Open the Terminal:
    • Open a terminal window on your Linux system. You can do this using the terminal emulator available on your desktop environment.
  2. Run the du -h Command:
    • Use the du -h command to display disk usage information in human-readable format (sizes in KB, MB, or GB).
  3. Sort the Output by Size:
    • Pipe the output of du -h to the sort command, specifying the -h flag to handle human-readable sizes correctly.

    • du -h | sort -h
    This sorts the directories and files by size, displaying the largest ones at the bottom.
  4. Reverse the Sort Order (Optional):
    • If you want to see the largest directories at the top, add the r flag to the sort command.

    • du -h | sort -rh
    This reverses the sort order, displaying the largest sizes at the top.
  5. Display Top N Results (Optional):
    • To limit the output to the top N results (e.g., top 10), use the head command.

    • du -h | sort -rh | head -n 10
    This shows only the top 10 largest directories.
  6. Incorporate into a Script (Optional):
    • If you frequently need to check disk usage, consider creating a shell script that automates these steps for convenience.

    • /bin/bash du -h | sort -rh | head -n 10
    Save this script and run it whenever you need a quick overview of disk usage.

By following these steps, you can efficiently analyze disk usage on your Linux system and identify the largest directories. Customizing the command for your needs and incorporating it into scripts can further enhance your workflow.