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

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