user3324120
user3324120

Reputation: 189

bash script that computes used diskspace percentage for given partition

I have a bash script that computes used diskspace percentage for given partition:


    df -k $devname | grep -v ^File | awk '{printf ("%i",$3*100 / $2); }

it doesn't work on a partition with long name because the name pushes the other columns to the next line, how do I fix this?

df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/mapper/VolGroup60-ROOT
                     2865493440 2222006740 497927968  82% /
tmpfs                 30913808         0  30913808   0% /dev/shm
/dev/sda1               495844    103347    366897  22% /boot

Upvotes: 2

Views: 3447

Answers (2)

salezica
salezica

Reputation: 76929

The -P (portability) option for df use a output format compliant with posix and keeps everything in one line. You can also simplify the awk part using sel.

Upvotes: 2

Saucier
Saucier

Reputation: 4360

Instead of parsing the entire "table" you could output the usage in percentage directly by using the --output parameter (see man 1 df for details):

$ df -k --output=pcent /dev/sda1
Use%
 13%

That should be a lot easier to filter.

E.g. by creating an array with readarray in Bash 4:

$ readarray -t -s 1 percentage < <(df -k --output=pcent /dev/sda1)
$ echo "${percentage[0]// /}"
13%

Assigning the output of df to an array line by line:

$ percentage=($(df -k --output=pcent /dev/sda1))
$ echo "${percentage[1]}"
13%

Upvotes: 6

Related Questions