How to find which folders and files are taking most of your space in Linux

Decluttering your filesystem can be one of the most tedious activities, but it is also vital when storage space is limited. In this article, we will streamline the process of identifying disk space hogs and help you keep your system as compact as possible.


List the largest directories.

Most user-related files are stored in the home directory. Use these commands to scrutinize space usage in your home directory:

du -h ~/ | sort -rh | head -n 10

du -h ~/: Calculates and displays the disk usage of all files and directories in your home directory in a human-readable format. If you would like to check the size of another directory replace  ~/ with the path of said directory.

sort -rh: Takes the output of the du command and sorts it in descending order of size, considering the human-readable format.

head -n 10: Takes the sorted output and displays only the first 10 lines, which corresponds to the top 10 largest directories in your home directory.

Output:

84K     /root/
20K     /root/snap
16K     /root/snap/lxd
12K     /root/var
12K     /root/.local
8.0K    /root/var/nfs
8.0K    /root/nfs
8.0K    /root/.ssh
8.0K    /root/.local/share

List the largest files in a directory

Identifying large files can be crucial in recovering significant amounts of disk space. The find command helps in this regard:

find ~/ -type f -exec du -h {} + | sort -rh | head -n 10

The new thing here is the find command that is used to search for files and directories within a specified location. Here's what the options used in this part mean:

~/: Specifies the starting directory for the search, which is your home directory.

-type f: Specifies that you're looking for files.

-exec du -h {} +: This part of the command executes the du -h command, which we already explained above on each found file.

{}: This is a placeholder that represents each file found by the find command.

+: This indicates that multiple filenames can be passed to a single invocation of du.

Output:

4.0K    /root/.ssh/known_hosts
4.0K    /root/.profile
4.0K    /root/.bashrc
4.0K    /root/.bash_history
0       /root/sshfs/file
0       /root/file
💡
It is also worth mentioning that some system directories may be unexpectedly consuming space. Look into /var (logs and data), /tmp (temporary files), and /usr (installed software) using the du command.