How to Use ls to List Directories and Their Total Sizes in Linux

Using the ls command in Linux is fundamental for listing files and directories within a specified location. However, to get a comprehensive view of directory sizes including their contents, additional tools and commands are necessary. This guide will show you how to effectively use ls along with other commands to list directories and calculate their total sizes.

Understanding Directory Size Calculation

By default, the ls command lists files and directories in a specified location without providing detailed size information for directories themselves. To determine the total size of directories, including all their contents recursively, we’ll use du (disk usage) command in combination with ls.

Step-by-Step Guide

1. Using ls with du to List Directory Sizes

To list directories and their total sizes in a specific location, follow these steps:

ls -l | grep '^d' | awk '{print $9}' | xargs -I {} du -sh {}

Let’s break down what each part of this command does:

  • ls -l: Lists all files and directories with detailed information.
  • grep '^d': Filters only directories (lines starting with ‘d’ in ls -l output).
  • awk '{print $9}': Extracts the directory names from the ls output (assuming the directory name is in the 9th column).
  • xargs -I {} du -sh {}: For each directory name {}, calculates its disk usage (du -sh) and outputs the total size.

Example Usage:

$ ls -l
total 16
drwxr-xr-x 2 user user 4096 Jun 19 15:00 dir1
drwxr-xr-x 2 user user 4096 Jun 19 15:01 dir2
-rw-r--r-- 1 user user   12 Jun 19 15:00 file1.txt
-rw-r--r-- 1 user user   23 Jun 19 15:01 file2.txt

$ ls -l | grep '^d' | awk '{print $9}' | xargs -I {} du -sh {}
4.0K    dir1
4.0K    dir2

In this example:

  • ls -l lists all files and directories.
  • grep '^d' filters only directories.
  • awk '{print $9}' extracts directory names.
  • xargs -I {} du -sh {} calculates and displays the disk usage (-sh for human-readable sizes) of each directory (dir1, dir2).

Conclusion

Using ls in combination with du allows you to list directories and their total sizes in Linux effectively. This method provides insights into disk usage within specified directories, facilitating better management of storage resources and file organization.

By following the steps outlined in this guide, you can enhance your ability to analyze directory sizes and optimize storage utilization on your Linux system.