Artificial Intelligence
Please fill the required field.

write a code to monitor disk space quota in linux


To monitor disk space quota in a Linux system, you can create a simple shell script that checks disk usage and sends an alert when usage exceeds a specified threshold. Below is an example of a script that accomplishes this task. ### Shell Script to Monitor Disk Space Quota ```bash #!/bin/bash # Set the threshold percentage (e.g. 80 for 80%) THRESHOLD=80 # Get the list of mounted file systems FILE_SYSTEMS=$(df -h --output=pcent,target | tail -n +2) # Loop through each file system while read -r line; do # Extract the usage percentage and mount point USAGE=$(echo "$line" | awk '{print $1}' | tr -d '%') MOUNT_POINT=$(echo "$line" | awk '{print $2}') # Check if the usage exceeds the threshold if [ "$USAGE" -ge "$THRESHOLD" ]; then echo "Warning: Disk usage on $MOUNT_POINT is at ${USAGE}%." fi done <<< "$FILE_SYSTEMS" ``` ### How to Use the Script 1. **Create the Script File**: Open a terminal and create a new script file: ```sh touch disk_space_monitor.sh ``` 2. **Edit the Script**: Open the script file in a text editor (e.g., `nano` or `vim`): ```sh nano disk_space_monitor.sh ``` Copy the script above and paste it into the file. Save and exit. 3. **Make the Script Executable**: Make the script executable by running: ```sh chmod +x disk_space_monitor.sh ``` 4. **Run the Script**: You can run the script manually: ```sh ./disk_space_monitor.sh ``` 5. **Automate the Monitoring**: To check disk space on a regular basis, you can add the script to your cron jobs by running: ```sh crontab -e ``` Add the following line to run the script every hour (as an example): ```sh 0 * * * * /path/to/disk_space_monitor.sh >> /path/to/disk_space_monitor.log 2>&1 ``` ### Notes - You may want to change the `THRESHOLD` variable to set the usage percentage that you consider critical. - This script checks all mounted filesystems and alerts if any of them exceed the specified threshold. - The output can be redirected to a log file for later review. - You might consider sending notifications (e.g., email or alerts via monitoring systems) in a production scenario. ### Additional Improvements Depending on your requirements, you may want to: - Send email alerts using `mail` command. - Implement logging with timestamps. - Check specific file systems instead of all mounted systems. - Enhance the script with better error handling.