UNIX Get An Alert When Disk Is Full

h‮/:sptt‬/www.lautturi.com
UNIX Get An Alert When Disk Is Full

There are a few ways you can get an alert when your disk is full in a UNIX-like operating system, such as Linux or macOS.

One way is to use the df command to check the available disk space on your system, and use a script or cron job to check the output of the df command regularly. If the available space falls below a certain threshold, you can send an alert using a command like mail or wall.

Here is an example script that will check the available disk space on the root (/) filesystem every 10 minutes, and send an alert via email if the available space falls below 1 GB:

#!/bin/bash

# Set the threshold for available disk space (in MB)
threshold=1000

while true; do
  # Get the available space on the root filesystem (in MB)
  available=$(df / | awk '/\/$/ {print $4}')

  # Check if the available space is below the threshold
  if [ $available -lt $threshold ]; then
    # Send an email alert
    echo "Low disk space on root filesystem: only $available MB available" | mail -s "Disk Space Alert" admin@example.com
  fi

  # Sleep for 10 minutes before checking again
  sleep 600
done

To use this script, save it to a file (e.g., disk_alert.sh) and make it executable with the chmod command:

chmod +x disk_alert.sh

Then, you can run the script in the background using the nohup command:

nohup ./disk_alert.sh &

This will start the script running in the background, and it will continue to run and check the available disk space until you stop it or the system is restarted.

Another option is to use a tool like inotifywait or fswatch to monitor the filesystem for changes, and trigger an alert when a new file is created and the available disk space falls below a certain threshold. This can be more efficient than using a script or cron job that checks the disk space periodically, as it will only trigger an alert when there is a change to the filesystem.

For example, the following command will use inotifywait to monitor the root filesystem for new file creations, and send an email alert if a new file is created and the available disk space falls below 1 GB:

inotifywait -m / -e create | while read path action file; do
  # Get the available space on the root filesystem (in MB)
  available=$(df / | awk '/\/$/ {print $4}')

  # Check if the available space is below the threshold
  if [ $available -lt 1000 ]; then
    # Send an email alert
    echo "Low disk space on root filesystem: only $available MB available" | mail -s "Disk Space Alert" admin@example.com
  fi
done

This command will run indefinitely, monitoring the root filesystem for new file creations and sending an alert if necessary. To stop the command, you can use Ctrl+C to interrupt it.

Created Time:2017-10-30 14:27:22  Author:lautturi