How do I get / available space with "df" and output it to a log file?

With the command of df, I can get something like:

Filesystem     1K-blocks     Used Available Use% Mounted on
/dev/root      197844228 15578648 180242500   8% /
devtmpfs         4101368        0   4101368   0% /dev
tmpfs             820648      292    820356   1% /run
tmpfs               5120        0      5120   0% /run/lock
tmpfs            1693720        4   1693716   1% /run/shm

What if I just want to keep the 180242500 number recorded of / and store it in a file (like disk-space-available.txt)

If I use df >> disk-space-available.txt it will store all the content while I just want the raw number in that file.

For example if there is something like this then it’s working:

df -OUTPUT=raw-available-number
180242500

What can I do?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

With df from GNU coreutils:

$> df --output=avail /
Avail
12345
$> df --output=avail / | grep -v Avail
12345

Solution 2

You can filter easily with awk, checking if the last field equal /, then print the corresponding 4th field:

df | awk '$NF == "/" { print $4 }' >> output

or:

df / | awk 'NR == 2 { print $4 }' >> output

Solution 3

If you don’t have the GNU version of ‘df’, you can use ‘stat’ to get the number and size of the available blocks.

stat --file-system --format="%f %S" /

You can then multiply them together to get the bytes available.

(stat=$(stat --file-system --format="%f %S" /) && echo $(( ${stat/ /*} )))

You can optionally convert it to human readable with numfmt --to=iec.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply