Calculating the Disk Space Used on Linux
Tagged with linux on January 1, 2025
There are multiple ways to calculate the disk space used on Linux, but most of them confuse the hell out of me. It’s only recently that I discovered that the file system reserves five percent of the available disk space for root operations. This was something that was originally designed for the extended file system in the 1990s, when disk drives were measured in megabytes.
Block Count and Reserved Block Count
This terminal command will show the “Block count” and the “Reserved block count” in bytes, but it’s the total partition size, not taking into account the file system itself:
tune2fs -l /dev/sda2 (that's a lowercase "L")
Use the appropriate device, of course. Anyway… The “du” and “df” commands return more accurate results. This command will show how much space has been used, without the reserved block count. It’s the command I was using when I wrote about Cinnamon Applets, Desklets, and Extensions:
df -h --total | tail -n 1 | awk '{ print $3 }'
With that, it’s just a matter of adding five percent to the result. Since I don’t know how to do that in the shell, I opted to do it in PHP. I have the php-cli package installed because I write this blog on my PC using Nginx and PHP.
The PHP Script
This PHP script uses the “shell_exec” function to retrieve the results of a shell command:
<?php $field = explode(' ' , trim( shell_exec( "df -h --total | tail -n 1 | awk '{ print $2,$3 }'" ) ) ); $reserved = substr( $field[0], 0, strlen( $field[0] ) -1 ) * .05; $unit = substr( $field[0], strlen( $field[0] ) -1 ) ; echo $reserved + substr( $field[1], 0, strlen( $field[1] ) -1 ) . $unit;
There’s probably a way to do this in BASH alone, but I’m not familiar enough with shell scripting to attempt more than I already have. There’s probably a more elegant way to do this in PHP as well, but it works as is. It isn’t 100% accurate because of rounding by the human-readable format, but it’s close. Unless you’re down to the last gigabyte on your drive, it won’t matter much anyway.
Reduce the Reserved Block Count
The “Reserved block count” of five percent made sense when drives were measured in megabytes. That’s a lot of wasted space on drives with gigabytes and terabytes available. You can reduce it to one percent with one command:
sudo tune2fs -m 1 /dev/sda2 (change the script above from .05 to .01)
Again, use the appropriate device. On a drive used only for storage, you can safely use 0 (“zero”) instead of 1 (“one”), which won’t reserve any blocks at all.
Image by [email protected] Larry Ewing and The GIMP, CC0, via Wikimedia Commons
← Previous ArticleNext Article →