Tech Blog :: Bash code to check free disk space

Dec 5 '10 12:15pm

Bash code to check free disk space

I have a script on a Linux server that downloads a bunch of very large files, and I want it to stop running if the disk is low on space. The way I found to do it is very verbose. Breaking it out line by line:

FREE=`df -H   # free space for all volumes
  | grep -E '^/dev/xvda3'    # the main disk
  | awk '{ print $4 }'    # the free space column
  | cut -d'G' -f1        # strip the G (for gigabytes)
  | awk -F '.' '{ print $1 }'`    # strip decimal parts
if [[ $FREE -lt 7 ]]; then
  echo "Less than 7GB free space left, stopping."
  exit 1

There's gotta be a simpler way to do that... anyone know what that is?

using df -k /dev/xvda3 will give you disk space in k with no decimal points or postfix letters which should help a bit in simplifying the script.

I use this : df -Pk /dev/mapper/VolGroup00-LogVol00 | sed 's/ */ /g' | cut -d' ' -f4 | tail -n 1
Because of longer volume name, it get span on multiple line. This also allow you to change the -f4 to other value to capture different columns