To keep track of how much disk space is used on your computer or server. This helps avoid running out of space and causing problems.
0
0
Disk space monitoring script in Bash Scripting
Introduction
You want to get a warning when disk space is low before it causes errors.
You manage a server and need to check disk space regularly.
You want to automate disk space checks and get alerts by email or logs.
You want to clean up files when disk space goes below a certain limit.
Syntax
Bash Scripting
#!/bin/bash THRESHOLD=80 USED=$(df / | tail -1 | awk '{print $5}' | sed 's/%//') if [ "$USED" -gt "$THRESHOLD" ]; then echo "Warning: Disk space is above $THRESHOLD% used. Current usage: $USED%" else echo "Disk space is OK. Current usage: $USED%" fi
Use df to check disk usage.
Use awk and sed to extract the percentage number.
Examples
This gets the disk usage percentage of the root directory.
Bash Scripting
# Check disk usage on root partition USED=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')
This sets a limit and prints a warning if usage is above it.
Bash Scripting
THRESHOLD=90 if [ "$USED" -gt "$THRESHOLD" ]; then echo "Disk almost full!" fi
Prints the current disk usage percentage.
Bash Scripting
echo "Disk usage is $USED%"Sample Program
This script checks the disk space used on the root partition. If usage is above 80%, it prints a warning. Otherwise, it says disk space is OK.
Bash Scripting
#!/bin/bash THRESHOLD=80 USED=$(df / | tail -1 | awk '{print $5}' | sed 's/%//') if [ "$USED" -gt "$THRESHOLD" ]; then echo "Warning: Disk space is above $THRESHOLD% used. Current usage: $USED%" else echo "Disk space is OK. Current usage: $USED%" fi
OutputSuccess
Important Notes
Make sure to give execute permission to the script using chmod +x scriptname.sh.
You can change THRESHOLD to any percentage you want to monitor.
Run the script manually or schedule it with cron for regular checks.
Summary
A disk space monitoring script helps avoid running out of space.
It uses simple commands like df, awk, and sed to get usage info.
You can customize the warning threshold and automate the script.