Find availble disk space in unix without parsing `df` output

1

When I type df -k ., I get the following output

Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda2       16512936 8650196   7023932  56% /

What I do is tail the last line and extract fourth field to get it correctly.

But if file system name is long, say e.g. /dev/niraj-asdsdsd-dsdsdsa, then df prints further details on a new line and using my logic I get 56% instead of 7023932.

So my question is, how to determine the exact free space in any situation?

Niraj

Posted 2015-01-05T09:34:45.387

Reputation: 249

Answers

3

The statutility, which is handy for getting file statistics, can also give you informations about file systems, just supply the -f option.

But be sure that you supply the mount point (e.g. /boot) and not the device file (/dev/sda1)! Because in the latter case stat will report statistics of the /dev file system, which is (on debian) a virtual filesystem and has nothing to do with the physical disc:

$ mount | grep sda1
/dev/sda1 on /boot type ext2 (rw,relatime,errors=continue,user_xattr,acl)
$ env stat -f /dev/sda2
 File: "/dev/sda1"
    ID: 0        Namelen: 255     Type: tmpfs
Block size: 4096       Fundamental block size: 4096
Blocks: Total: 2560       Free: 2560       Available: 2560
Inodes: Total: 497355     Free: 496852
$ env stat -f /boot
  File: "/boot"
    ID: fe082d7c0c42ea6f Namelen: 255     Type: ext2/ext3
Block size: 1024       Fundamental block size: 1024
Blocks: Total: 99150      Free: 52490      Available: 47370
Inodes: Total: 25688      Free: 25355
  • The difference between the Free and Available count results from the reserved blocks for root.
  • I used env to make sure that not the builtin stat command of your shell (which might or might not provide all the used options) is used.

So, to answer your question, you can use a customized (-c) stat output format to get the avalable space (%a) on /:

$ env stat -f -c %a /
1711744

This is in blocks, so be clever and let the system do a multiplication with the block size in KB units (%S/1024) by piping the output into the bc calculator:

$ env stat -f -c '%a*%S/1024' / | bc
6846976

Let's check with df:

$ df /
Filesystem     1K-blocks     Used Available Use% Mounted on
/dev/sda2       25066604 16939628   6846976  72% /

Fine, same number reported!

mpy

Posted 2015-01-05T09:34:45.387

Reputation: 20 866

0

Niraj - Have you looked at the di utility? This might offer at least an easier way to extract the data you need, it offers a CSV format output of the drive space.

di -c

Optichip

Posted 2015-01-05T09:34:45.387

Reputation: 649