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



Question:

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.


Solution:1

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.


Solution:2

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  


Solution:3

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


Solution:4

You can pipe to a grep that just extracts digits:

df --output=pcent /mount/point | grep -o '[0-9]*'  

See it live:

$ echo "Use%  > 83%" | grep -o '[0-9]*'  83  


Solution:5

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'


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »