There are several questions and answers on askubuntu about seeing disk space from the command line.
Naturally, df is the go-to tool for this.
However I want a script at login to raise an alert if the free disk space is below some threshold.
Unfortunately df seems to use arbitrarily sized columns and I'm not sure how to extract just the value from the column I'm interested in.
For example:
$ df /dev/mapper/root
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/root 2563092 1649968 763212 69% /
$ df /dev/mapper/root | tail -n 1
/dev/mapper/root 2563092 1649968 763212 69% /
$ df /dev/mapper/root | tail -n 1 | cut -d ' ' -f 9
763212Really I want the fourth column, yet I must ask for the ninth.
Is there an easier way to either extract the column's value from df's output, or another way altogether to access this value.
3 Answers
Just realized that this isn't what was asked for, this shows an alert if the space used is greater than a predefined threshold. I'll leave it for further reference though.
You could use something like the script below
#!/bin/bash
X=
X=$(du -sc | awk 'NR < 2' | awk '{ print $1 }')
if [ $X -gt 999000 ]; then message="Already using `du -sch | awk 'NR <2' |awk '{ print $1 }'` KB"
echo $message | mail -s "File System Full Warning"
fiX holds the number of KB used, if greater than 999000 it emails a warning message.
1I'd use an awk to only deal with the second line (skips the first here) and get you your column:
$ df /dev/mapper/sil_acababdfabcf1 | awk 'NR==2 {print $4}'
11903752 1 If you're on Ubuntu 14.04 or later, df can output only the values you want it to:
$ df --output=avail / Avail
15127808From man df:
--output[=FIELD_LIST] use the output format defined by FIELD_LIST, or print all fields if FIELD_LIST is omitted.
...
FIELD_LIST is a comma-separated list of columns to be included. Valid
field names are: 'source', 'fstype', 'itotal', 'iused', 'iavail',
'ipcent', 'size', 'used', 'avail', 'pcent' and 'target' (see info
page).As noted by Drew Noakes, this ability was added in GNU coreutils 8.21, and so isn't available in older versions of Ubuntu.
For selecting fields, awk is a far better tool than cut, and you can build on Jan's answer for that after picking the fields you want df to output.