How to capture disk usage percentage of a partition as an integer?

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...

df --output=pcent /mount/point | tr -dc '0-9'

Not sure if sed is faster, but I can't ever remember the sed values.


Here's awk solution:

$ df --output=pcent /mnt/HDD | awk -F'%' 'NR==2{print $1}'   
 37

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:

bash-4.3$ df --output=pcent / | while IFS= read -r line; do 
>     ((c++)); 
>     [ $c -eq 2 ] && echo "${line%\%*}" ;
> done
 74

And for fun, alternative sed via capture group and -r for extended regex:

df --output=pcent | sed -nr '/[[:digit:]]/{s/[[:space:]]+([[:digit:]]+)%/\1/;p}'

sed solution

df --output=pcent /mount/point | sed '1d;s/^ //;s/%//'
  • 1d delete the first line
  • ; to separate commands
  • s/^ // remove a space from the start of lines
  • s/%// remove % sign