Is it possible to use ls in Unix to list the total size of a sub-directory and all its contents?
By itself, ls
does not provide a command-line option to display the total size (sum of all files) of a subdirectory. The ls
utility lists filenames and their attributes, but it doesn’t output a single cumulative size.
To get the total size of a directory (including all its files and subfolders), use du
(disk usage) instead. For a human-readable summary:
du -sh /path/to/directory
-s
: Summarize the total size of the directory rather than listing each file.-h
: Show sizes in a “human-readable” format (e.g., KB, MB, GB).
If you run:
du -sh /path/to/directory/*
you get individual human-readable sizes for every item inside directory
, as well as the total for each subfolder.
Why Not ls
?
ls -l
lists files and their sizes but shows per-file information rather than a total.ls -s
displays disk blocks used by each file. Again, this doesn’t aggregate the values into a single total.
Hence, du
is the standard tool whenever you need the total size of a directory on Unix-like systems.
Further Learning
To strengthen your command-line skills and complement them with robust coding expertise, check out the following courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews
Build a deep understanding of the fundamental data structures and algorithms necessary for writing efficient programs. -
Grokking the Coding Interview: Patterns for Coding Questions
Learn common patterns behind coding problems, enabling faster and more reliable solutions in both interviews and real-world development.
By combining solid command-line skills (like using du
effectively) with strong algorithmic foundations, you’ll be well-prepared to tackle a wide range of technical tasks.