NASutils Knowledge BaseUnofficialPolski

Bash · lesson 24 of 30 · Files and errorsRead df

Read the second line of df -P -k and compare the percentage with a limit.

Programming on the NAS › Bash in 30 lessons

24-free-space.sh Download 24-free-space.sh

#!/usr/app/TurboShell/bin/bash
# Free space of the volume that holds a folder
set -euo pipefail
folder=${1:-.}
limit=${2:-90}
if [[ ! $limit =~ ^(0|[1-9][0-9]?|100)$ ]]; then
  echo "The limit is a number from 0 to 100"
  exit 2
fi

{
  read -r _
  read -r _ total _ free percent _
} < <(df -P -k "$folder")

used=${percent%\%}
echo "$((free / 1024 / 1024)) GiB of $((total / 1024 / 1024)) GiB are free, $used percent are used"
if ((used >= limit)); then
  echo "The limit is $limit percent"
  exit 1
fi

Terminal

$ bash 24-free-space.sh .
1033 GiB of 1327 GiB are free, 22 percent are used
$ bash 24-free-space.sh . 0; echo "exit code $?"
1033 GiB of 1327 GiB are free, 22 percent are used
The limit is 0 percent
exit code 1

The numbers or the date differ on your NAS.

Exercise

Check two folders one after the other.