Monitoring disk space on Ubuntu is crucial to prevent system issues, especially on servers where low disk space can affect performance and stability. Regular disk checks can help you anticipate when space is running low and make adjustments before it becomes a problem.
The df command is one of the simplest ways to check disk space on Ubuntu. It provides an overview of file system disk usage. Running df without any options gives you a general idea of space usage across mounted filesystems.
df
df -h
The -h option displays sizes in a human-readable format (e.g., KB, MB, GB). Here’s an example output:
-h
Filesystem Size Used Avail Use% Mounted on /dev/sda1 100G 45G 55G 45% / tmpfs 500M 1.2M 499M 1% /tmp
While df provides an overview, the du command gives a more detailed breakdown, showing usage by individual files and directories. To analyze disk usage for a specific directory, run:
du
du -h /path/to/directory
If you want a summary of the directory size, use the -s option:
-s
du -sh /path/to/directory
This command displays the total size of the directory in a human-readable format, which is useful for quickly identifying large directories.
ncdu is a command-line disk usage analyzer that provides a more interactive experience. It needs to be installed first:
ncdu
sudo apt update && sudo apt install ncdu
To use ncdu, simply run it with a directory:
ncdu /
It will scan the directory and give you a list of files and directories sorted by size, making it easy to identify what's using the most space.
To find large files, you can use the find command. Here’s an example that finds files over 100 MB in the /home directory:
find
/home
find /home -type f -size +100M
This command lists all files over 100 MB in size. You can adjust the size as needed (e.g., +500M for 500 MB or +1G for 1 GB).
+500M
+1G
For regular disk checks, you can create a simple script that runs daily and sends alerts if space is running low. Here’s an example script that checks if the root filesystem has less than 10 GB available and sends a message to the console.
#!/bin/bash threshold=10 available=$(df -h / | grep '/' | awk '{print $4}' | sed 's/G//') if (( available < threshold )); then echo "Warning: Less than $threshold GB available on root filesystem." fi
Save this script as check_disk_space.sh, make it executable, and schedule it to run daily using cron:
check_disk_space.sh
chmod +x check_disk_space.sh
crontab -e
Add the following line to run the script daily at 2 am:
0 2 * * * /path/to/check_disk_space.sh
Monitoring disk space on Ubuntu is essential for smooth system operation, especially in server environments. Using commands like df, du, and find, along with tools like ncdu and automation scripts, you can efficiently manage and monitor disk usage, helping to prevent potential issues caused by low disk space.