Checking disk space

Here's a script for quickly checking on how much disk space you have on a system and how much of it is in use. It certainly beats using a calculator to tally up the columns in "df -k" output.

We're not looking for precision here. After all, disk usage changes very frequently. We don't want to see this information extended to ten decimal places. We just want a "feel" for how much space is in use and how much is still available. So, we report disk space in gigabytes and calculate a percentage. We round up both the total disk space and disk space used to the next gigabyte and the percentage used to the next percent. The generated report will look something like this:

# ./chkDiskSpace
total: 308 GB
 used: 32 GB
11% in use

The script includes two subroutines -- one to round up a number and one to convert kilobytes to gigabytes. We could have used the "df -h" to report disk usage in GB instead of KB, but then we'd have to concern ourselves with the decimal points and occassional datapoints reported in KB because of their small size and that would complicate everything.

We squeeze strings of blanks into single blanks so that we can split the "df -k" output on the blanks in between the columns and skip over the headings before we run through each line of data.

The script also skips over swap space and NFS mounted partitions by ignoring any lines in the "df -k" output that don't start with the tell-tale "/dev". It also doesn't report on unmounted file systems; it's only looking at mounted drives.


# round up to next integer
sub roundup {
    my $n = shift;
    return(($n == int($n)) ? $n : int($n + 1))

sub conv2g {
    my $n = shift;


# get disk space report
open(STATS, "df -k|") || die "$!";

# init params
my $lineNo  = 0;
my $totUsed   = 0;
my $totSpace  = 0;

while ($input = <STATS>) {
  if ($lineNo++ != 0) {         # Skip column headings
    $input =~ s/\s+/ /g;        # squeeze out blanks
    next if $input !~ /^\/dev/; # skip over NFS mounts, swap
    my @columns = split(/ /, $input);
    $totSpace += $columns[1];
    $totUsed += $columns[2];

$percent = $totUsed / $totSpace;
$pct=roundup($percent * 100);

print "total: $totSpace GB\n";
print " used: $totUsed GB\n";
print "$pct% in use\n";

You could set up a script like this to email you the results or email you the results only if the percentage of free disk space warrants your attention. Alternately, you might just use it when you're making plans for upgrading disks on some of your file servers and want a quick report on whether they're hurting for space or should be in good shape for the next year or two.

This article is published as part of the IDG Contributor Network. Want to Join?

To express your thoughts on Computerworld content, visit Computerworld's Facebook page, LinkedIn page and Twitter stream.
7 Wi-Fi vulnerabilities beyond weak passwords
Shop Tech Products at Amazon