In this article, we will walk through the process of creating a shell script that monitors the disk space and sends an alert when the available space falls below a certain threshold. We will use the df command to check the available disk space and the mail command to send the alert.
Step 1: Check the Available Disk Space
The first step in our shell script is to check the available disk space on the server. We can use the df command to do this. The df command displays the amount of available disk space on the file system.
To check the available space on the root
file system (/), we can use the following command:
This will display the available space in human-readable format (i.e., in GB or MB). The output will look something like this:
The Avail column shows the available space on the file system.
Step 2: Set the Threshold and Check the Available Space
Next, we need to set a threshold for the available space. When the available space falls below this threshold, we will send an alert. For example, we might set the threshold at 10 GB.
To check if the available space is below the threshold, we can use the -lt
operator, which stands for “less than”. Here is an example of an if statement that checks if the available space is less than 10 GB:
The df command is used to get the available space on the root file system (/). The awk command is used to extract the fourth column ($4), which is the available space. The tail command is used to get the last line of the output (since the df command also includes a header line). The -lt
operator is used to compare the available space to the threshold (10 GB).
Step 3: Sending Email Alerts
You can incorporate the mail command into a shell script to automatically send an alert when the available disk space falls below a certain threshold. To do this, you can use an if statement to check the available space (as described in the previous section), and then use the mail command to send the alert if the available space is below the threshold.
This command will send an email to [email protected]
with the subject “Low Disk Space Alert” and the body “Attention: The available disk space on the server is running low. Please take action to free up some space. Thank you, Server Admin”.
Final Script: Check Disk Space and Send Email Alerts
For example, here is a shell script that checks the available space on the root file system (/) and sends an alert if it falls below 10 GB:
I hope this helps you understand how to send an alert when the available disk space falls below a certain threshold in Linux. You can customize the threshold and the alert message to suit your specific needs.