2

I have a disk script like this:

#!/bin/bash

filesys=(
/
)
[ -f "$(pwd)/filesys.conf" ] && filesys=($(<$(pwd)/filesys.conf))

date=$(date +"%d\/%m\/%Y")

df -P "${filesys[@]}" |
sed -ne 's/^.* \([0-9]\+\)% \(.*\)$/'$date', \2, \1%/p' > disk.log

I have filesys.conf for work which filesystem:

/
/run

And this is output (disk.log):

23/05/2016, /, 78%
23/05/2016, /run, 0%

Question:

I need filesys.conf because server filesystems always change, conf file easy for me. But I need to add usage parameter in filesys.conf too like this:

/,90
/run,99

If / usage greater than 90, /run usage greater than 99, write to log file.

How can I do this?

onur
  • 5,647
  • 3
  • 23
  • 46
  • Do you want to write to `disk.log` or another log file? You can do some postprocessing with, for example, awk. There you can compare the values and decide what to do. – fedorqui May 23 '16 at 07:55
  • Write to `disk.log`. I need to write just greater than this usage. – onur May 23 '16 at 07:57

1 Answers1

2

Let's create a bash associative array from the file filesys.conf on the form assoc[file system]=threshold. This way, we can loop over it and compare against the output of df -P.

Given the file:

$ cat filesys.conf
/,90
/dev,25

We store it in the array with (source: Bash reading from a file to an associative array):

declare -A assoc
while IFS=, read -r -a array;
do
    assoc[${array[0]}]=${array[1]}
done < filesys.conf

So now the values are:

$ for k in "${!assoc[@]}"; do echo "${k} --> ${assoc[$k]}"; done
/dev --> 25
/ --> 90

Now it is just a matter of processing the output of df with, for example, awk:

mydate=$(date "+%d/%m/%Y")
for k in "${!assoc[@]}"
do
    df -P "${k}" | awk 'NR==2 && $(NF-1)+0 > limit {print date, fs, $(NF-1)}' OFS=, fs="$k" date=mydate limit="${assoc[$k]}"
done >> disk.log

This pipes df to awk. There, we check the second line (the first one is the header, which apparently cannot be removed from the output (man df does not mention it)) and, in there, the value of the penultimate column. If its value is bigger than the given threshold, we print the desired output.

Note the trick of $(NF-1)+0 to cast the Use% column to int: the format 13% gets converted into 13.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598