Alex Georgiev

Monitor disk space usage with BASH

Created April 4, 2021


If you've ever had to deal with a Linux server that was out of disk space at some point you know that it's important not to run into the same situation again. In most cases, the server can run out of disk space due to huge session files or even an error log file growing up to hundreds of Gigabytes.

However, sometimes you might get the famous "No space left on device" error message without knowing what is taking the disk space. With few simple BASH commands, you can quickly check which folders and files are the most disk space consuming on your system

Script summary

The first step you can perform if you experience this issue is the check the disk space usage on your server using df. The command displays the amount of disk space available on the file system containing each file name argument.

The get an idea of what the output of the command is here is an example. We will also add the -h argument or --human-readable to get a more nice output of the command.

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        2.0G     0  2.0G   0% /dev
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           2.0G  209M  1.8G  11% /run
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
/dev/xvda        30G   12G   16G  43% /
tmpfs           400M     0  400M   0% /run/user/0

As you can see the disk space usage is totally fine and we're a far way from running into issues for the moment. However, this can quickly change if we do a large backup of our application or website or as already mentioned the session folder grows dramatically or if we simply modify our code and this triggers an error which then gets logged and then the error_log can grow pretty quickly as well.

With the df command we can quickly check if the disk space was exceeded on the / partition or for example if /tmp or /var are separate partitions the disk space can be exceeded there if the assigned amount of disk space was not sufficient or if simply some of the bad scenarios we've already mentioned had happened.

Another useful command we can use to locate file space usage is du. You can quickly check which are the most disk space consuming directories on your server. An example command will be the following:

du -ch --max-depth=2 / 2>/dev/null | sort -rh | head -15

Where: -c will produce a grand total of the disk usage, -h is again for human-readable output.

Where: -h is for human-readable output.

Checkout our latest product - the ultimate tailwindcss page creator