I would like a method to capture the disk usage of a particular partition, by using the directory where the partition is mounted. The output should just be an integer with no padding or following symbols, as I'd like to save it in a variable.
I've used df --output=pcent /mount/point
, but need to trim the output as it has an unnecessary header, single space padding before the value, and a % symbol following the value like so:
Use%
83%
In this case the output I would like would simply be 83
. I'm not aware of any drawbacks to using the output of df
, but am happy to accept other methods that do not rely on it.
I'd use...
Not sure if sed is faster, but I can't ever remember the sed values.
Here's awk solution:
Basically what happens here is that we treat '%' character as field separator ( column delimiter ), and print first column $1 only when number of records equals to two ( the
NR==2
part )If we wanted to use
bash
-only tools, we could do something like this:And for fun, alternative
sed
via capture group and-r
for extended regex:sed
solution1d
delete the first line;
to separate commandss/^ //
remove a space from the start of liness/%//
remove%
signYou can pipe to a
grep
that just extracts digits:See it live:
I came upon a server where --output=pcent was not yet implemented, so I used the normal output, filtered by column, followed by the regex:
df /mount/point | awk '{print $5}' | tr -dc '0-9'
Bash two-step solution
Being somewhat of a bash (Borne Again SHell) fan the last year I thought I'd propose a solution using it.
df
output to variableDF_PCT
.DF_PCT
and displays it on screen.5
in this case) is generated.Here is an another solution: