How to Write a Bash Script to Check Disk Space: A Simple Guide
Disk space management is an essential task for system administrators, developers, and anyone managing a server. Running out of disk space can lead to severe system issues, including slow performance, data loss, or even system crashes. To keep track of disk usage, a reliable and simple solution is writing a bash script to check disk space regularly. In this article, we’ll show you how to create such a script and discuss some examples to make the process easy and efficient.
Why Is Disk Space Important?
Disk space is a finite resource on your system. When it runs low, it can cause various problems, from applications crashing to the operating system failing to function properly. As a result, monitoring your disk space usage is critical for ensuring smooth system performance. Fortunately, with the power of bash scripting, you can automate disk space monitoring and prevent issues before they arise.
Understanding the Basics of Bash Scripting
Bash (Bourne Again Shell) is a popular shell used for scripting in Unix-based systems like Linux and macOS. It allows you to write commands and automate tasks. A bash script to check disk space is essentially a series of commands that you run in sequence to monitor how much space is left on your disk drives.
Before we dive into the script itself, let’s first take a look at the basic command to check disk space in Linux systems: the df command. The df command stands for “disk filesystem,” and it provides a summary of disk space usage for all mounted filesystems.
df -h
The -h flag tells the command to display the output in a human-readable format (i.e., with units like GB or MB). This is the output that we want to monitor with our script.
Writing a Basic Bash Script to Check Disk Space
Now that we know how to check disk space with the df command, let’s create a bash script that can automate this task. Here’s a simple bash script to check the disk space of your system:
#!/bin/bash # Bash script to check disk space echo "Checking disk space..." df -h
This script is very simple. When you run it, it will print out the disk usage of all mounted filesystems in a human-readable format. To use the script:
- Create a new file: `nano check_disk_space.sh`
- Paste the code above into the file
- Make the script executable: `chmod +x check_disk_space.sh`
- Run the script: `./check_disk_space.sh`
Once executed, the script will display the current disk space usage in a friendly format. However, if you want to add more functionality, you can modify this basic script to perform additional tasks like sending alerts or checking specific directories.
Adding Alerts to the Bash Script
To make the script more useful, let’s add a feature that alerts us when disk space usage exceeds a certain threshold. For example, if the available disk space falls below 10%, we can send a warning message. Here’s how you can modify the script to include this feature:
#!/bin/bash
# Bash script to check disk space and send an alert if below 10%
THRESHOLD=10
USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g')
echo "Disk usage is at ${USAGE}%"
if [ $USAGE -gt $THRESHOLD ]; then
echo "Warning: Disk space usage is above ${THRESHOLD}%"
fi
Here’s what this script does:
- THRESHOLD=10: Sets the threshold for disk space usage at 10%.
- USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//g'): This command retrieves the disk usage percentage for the root directory (`/`) and removes the percent symbol.
- If the disk usage exceeds the threshold, a warning message is displayed.
Now, every time you run this script, it will check if the disk space usage is above 10%. If it is, a warning message will appear, allowing you to take action before running out of space.
Checking Multiple Directories
What if you want to check the disk space usage of multiple directories? You can modify the script to monitor different directories. Here’s an example of how to check the disk space of multiple directories, such as `/home` and `/var`:
#!/bin/bash
# Bash script to check disk space for multiple directories
DIRECTORIES=("/home" "/var")
THRESHOLD=10
for DIR in "${DIRECTORIES[@]}"
do
USAGE=$(df $DIR | grep $DIR | awk '{ print $5 }' | sed 's/%//g')
echo "Disk usage for $DIR is at ${USAGE}%"
if [ $USAGE -gt $THRESHOLD ]; then
echo "Warning: Disk space usage for $DIR is above ${THRESHOLD}%"
fi
done
This script checks the disk space usage for both `/home` and `/var` directories. If any of them exceeds the specified threshold, a warning message will be displayed. You can easily add more directories to monitor by appending them to the DIRECTORIES array.
Automating the Script with Cron Jobs
To make sure your system’s disk space is checked regularly, you can automate the script by scheduling it with cron jobs. Cron jobs are used to run scripts at specified intervals (e.g., daily, weekly, monthly). Here’s how to set up a cron job to run the disk space check script every day at 8:00 AM:
- Open the crontab configuration by typing: `crontab -e`
- Add the following line to schedule the script:
0 8 * * * /path/to/check_disk_space.sh
This cron job will execute the script at 8:00 AM every day. Be sure to replace `/path/to/check_disk_space.sh` with the actual path to your script file. You can adjust the schedule as needed.
Conclusion
Creating a bash script to check disk space is a simple and effective way to monitor your system’s storage usage. By automating the process, you can prevent disk space issues from causing problems. Whether you need to monitor a single directory or multiple directories, bash scripting provides a versatile and powerful solution. Add alerts, automate the script with cron jobs, and stay ahead of potential disk space problems. It’s an easy task that can make a big difference in maintaining the health of your system.

Komentarze (0) - Nikt jeszcze nie komentował - bądź pierwszy!