Introduction :
Monitoring the usage of disc space on a Linux server is a key responsibility for system administrators. Insufficient diskspace can lead to system crashes, data loss, and reduced performance. Frequently checking the server disk usage can help you understand how much storage space you have remaining on your server. You may also use this data to predict when your server’s disk storage will run out of space. This post will share simple bash script to check linux server disk space and then help you automate this task using crond. As example, the script send out email once the percentage of usage reaches a certain threshold, such as 90%.
1. Copy this script put in your linux sever :
#!/bin/bash # Set the threshold threshold=90 # Get the current date and time date=`date +%Y-%m-%d:%H:%M:%S` # Obtain a list of file systems, excluding tmpfs and /boot fs_list=`df -h | awk '{print $1}' | grep -vE "^Filesystem|tmpfs|/boot"` # Initialize variables for table output="Date: $date\n\nFile System,Total,Free,Usage\n" # Loop all the file systems for fs in $fs_list; do # Get the total, free, and usage values in MB total=`df -h $fs | awk '{print $2}' | tail -1 | tr -d 'M'` free=`df -h $fs | awk '{print $4}' | tail -1 | tr -d 'M'` usage=`df -h $fs | awk '{print $5}' | tail -1 | tr -d '%'` # Add the values to the table output="$output$fs,$total,$free,$usage\n" # Check if usage is exceed the threshold if [ $usage -ge $threshold ]; then # Send email with the output echo -e $output | mail -s "Disk Space Alert: $fs usage at $usage%" [email protected] fi done # Print the output echo -e $output
2. Make the script executable.
#chmod +x /root/script.sh
3. You can configure cronjob to automate the checking and email trigger.
0 2 * * * /root/script.sh
Note : This schedule runs the script at 2:00 AM daily.
Conclusion :
Monitoring the usage of disk space on a linux server is essential for system performance and stability. By using a simple bash script to check disk space and trigger email using cronjob, you can immediately identify potential issues and take preventative steps before they become serious.