How to check free disk space in Linux
How to Check Free Disk Space in Linux
Managing disk space is a critical aspect of Linux system administration. Whether you're running a personal desktop, managing a server, or working in a development environment, knowing how to monitor and check available disk space can prevent system failures, performance issues, and data loss. This comprehensive guide will walk you through various methods to check free disk space in Linux, from basic commands to advanced monitoring techniques.
Table of Contents
- [Why Monitoring Disk Space is Important](#why-monitoring-disk-space-is-important)
- [Basic Commands for Checking Disk Space](#basic-commands-for-checking-disk-space)
- [Advanced Disk Space Analysis](#advanced-disk-space-analysis)
- [GUI Methods for Desktop Users](#gui-methods-for-desktop-users)
- [Automated Monitoring and Alerts](#automated-monitoring-and-alerts)
- [Troubleshooting Common Issues](#troubleshooting-common-issues)
- [Best Practices](#best-practices)
- [Conclusion](#conclusion)
Why Monitoring Disk Space is Important
Before diving into the commands, it's essential to understand why regular disk space monitoring is crucial:
- System Stability: When disk space reaches 100%, your system can become unstable or crash
- Performance Impact: Low disk space can significantly slow down your system
- Application Failures: Many applications require temporary space to function properly
- Log Management: System logs can quickly consume disk space if not monitored
- Database Operations: Databases need free space for operations and backups
Basic Commands for Checking Disk Space
Using the `df` Command
The `df` (disk free) command is the most commonly used tool for checking disk space in Linux. It displays information about mounted filesystems.
Basic `df` Usage
```bash
df
```
This basic command output shows:
- Filesystem: The device or filesystem name
- 1K-blocks: Total space in 1KB blocks
- Used: Used space in 1KB blocks
- Available: Available space in 1KB blocks
- Use%: Percentage of space used
- Mounted on: Mount point location
Human-Readable Format
For easier reading, use the `-h` flag to display sizes in human-readable format:
```bash
df -h
```
Example output:
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 20G 15G 4.2G 79% /
/dev/sda2 100G 45G 50G 48% /home
tmpfs 2.0G 0 2.0G 0% /dev/shm
```
Checking Specific Filesystems
To check a specific filesystem or directory:
```bash
df -h /
df -h /home
df -h /var/log
```
Additional Useful `df` Options
```bash
Show filesystem types
df -T
Display inode information
df -i
Show only local filesystems
df -l
Exclude specific filesystem types
df -x tmpfs -x devtmpfs
```
Using the `du` Command
The `du` (disk usage) command shows directory space usage, which is helpful for identifying which folders consume the most space.
Basic `du` Usage
```bash
Show disk usage of current directory
du
Human-readable format
du -h
Show total size only
du -sh
Show sizes for all subdirectories
du -h --max-depth=1
```
Finding Large Directories
To identify the largest directories in your system:
```bash
Find largest directories in root
sudo du -h --max-depth=1 / 2>/dev/null | sort -hr
Find largest directories in home
du -h --max-depth=1 ~/ | sort -hr
Find largest files and directories
du -ah /path/to/directory | sort -hr | head -20
```
Example output:
```
5.2G /var
3.1G /usr
2.8G /home
1.1G /opt
512M /boot
```
Advanced Disk Space Analysis
Using `ncdu` - Interactive Disk Usage Analyzer
`ncdu` (NCurses Disk Usage) provides an interactive interface for analyzing disk usage:
```bash
Install ncdu (Ubuntu/Debian)
sudo apt install ncdu
Install ncdu (Red Hat/CentOS)
sudo yum install ncdu
Run ncdu
ncdu /
Analyze specific directory
ncdu /home
```
Using `lsblk` - List Block Devices
The `lsblk` command displays information about block devices in a tree format:
```bash
Basic usage
lsblk
Show filesystem information
lsblk -f
Show size information
lsblk -o NAME,SIZE,USED,AVAIL,FSTYPE,MOUNTPOINT
```
Finding Large Files with `find`
To locate large files consuming disk space:
```bash
Find files larger than 100MB
find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null
Find files larger than 1GB
find / -type f -size +1G -exec ls -lh {} \; 2>/dev/null
Find largest files in a directory
find /path/to/directory -type f -exec du -h {} + | sort -hr | head -20
```
Using `iostat` for I/O Statistics
Monitor disk I/O along with space usage:
```bash
Install sysstat package
sudo apt install sysstat # Ubuntu/Debian
sudo yum install sysstat # Red Hat/CentOS
Display disk usage statistics
iostat -d 1
```
GUI Methods for Desktop Users
GNOME Disk Usage Analyzer (Baobab)
For GNOME desktop users:
```bash
Install Baobab
sudo apt install baobab
Launch from command line
baobab
```
KDE KDirStat
For KDE users:
```bash
Install KDirStat
sudo apt install kdirstat
Launch
kdirstat
```
File Manager Integration
Most Linux file managers display disk usage information:
- Nautilus (GNOME): Shows available space in the sidebar
- Dolphin (KDE): Displays space information in the status bar
- Thunar (XFCE): Shows disk usage in properties
Automated Monitoring and Alerts
Creating Disk Space Monitoring Scripts
Create a simple script to monitor disk usage:
```bash
#!/bin/bash
disk_monitor.sh
THRESHOLD=80
EMAIL="admin@example.com"
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
usage=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
partition=$(echo $output | awk '{ print $2 }')
if [ $usage -ge $THRESHOLD ]; then
echo "WARNING: $partition is $usage% full" | mail -s "Disk Space Alert" $EMAIL
fi
done
```
Make it executable and add to crontab:
```bash
chmod +x disk_monitor.sh
Add to crontab to run every hour
crontab -e
0 /path/to/disk_monitor.sh
```
Using `watch` for Real-time Monitoring
Monitor disk space in real-time:
```bash
Update every 2 seconds
watch -n 2 df -h
Monitor specific directory
watch -n 5 'du -sh /var/log'
```
Troubleshooting Common Issues
Issue 1: Command Shows Different Results
Problem: `df` and `du` show different disk usage for the same directory.
Solution: This often happens due to deleted files that are still held open by processes:
```bash
Find processes with deleted files
lsof +L1
Restart services holding deleted files
sudo systemctl restart service_name
```
Issue 2: Permission Denied Errors
Problem: Getting permission errors when scanning directories.
Solution: Use `sudo` for system directories:
```bash
sudo du -sh /var
sudo find / -name "*.log" -size +100M 2>/dev/null
```
Issue 3: Filesystem Shows 100% but Files Don't Add Up
Problem: Disk shows full but can't find large files.
Causes and Solutions:
1. Reserved space: ext2/3/4 filesystems reserve 5% for root
```bash
# Check reserved space
tune2fs -l /dev/sda1 | grep -i reserved
# Reduce reserved space (careful!)
sudo tune2fs -r 0 /dev/sda1
```
2. Inode exhaustion: No more inodes available
```bash
# Check inode usage
df -i
# Find directories with many files
find / -xdev -type d -exec bash -c 'echo "$(ls -1 "$1" | wc -l) $1"' _ {} \; | sort -n
```
3. Hidden or deleted files: Files deleted but still open
```bash
# Find deleted files still in use
lsof | grep deleted
```
Issue 4: Slow Response from Commands
Problem: Disk space commands are running slowly.
Solutions:
```bash
Skip network filesystems
df -l
Exclude specific filesystem types
df -x nfs -x cifs
Use timeout for unresponsive mounts
timeout 30s df -h
```
Best Practices
Regular Monitoring Schedule
1. Daily: Check critical systems and servers
2. Weekly: Review disk usage trends
3. Monthly: Analyze growth patterns and plan capacity
Setting Up Proper Thresholds
- Warning: 80% disk usage
- Critical: 90% disk usage
- Emergency: 95% disk usage
Disk Space Management Tips
1. Log Rotation: Implement proper log rotation
```bash
# Configure logrotate
sudo vim /etc/logrotate.conf
```
2. Temporary File Cleanup: Regular cleanup of temp directories
```bash
# Clean tmp directories
sudo find /tmp -type f -atime +7 -delete
sudo find /var/tmp -type f -atime +30 -delete
```
3. Package Cache Management:
```bash
# Clean package cache (Debian/Ubuntu)
sudo apt autoclean
sudo apt autoremove
# Clean package cache (Red Hat/CentOS)
sudo yum clean all
sudo dnf clean all
```
Documentation and Tracking
- Maintain a disk usage baseline
- Document filesystem layouts
- Track growth trends
- Plan for capacity upgrades
Advanced Commands Summary
Here's a quick reference of advanced disk space checking commands:
```bash
Comprehensive disk analysis
df -h && echo "---" && lsblk -f && echo "---" && du -sh /* 2>/dev/null | sort -hr
Find top 10 largest directories
du -h --max-depth=1 / 2>/dev/null | sort -hr | head -10
Monitor real-time disk usage
watch -n 1 'df -h; echo ""; du -sh /var/log /tmp'
Check for duplicate files
fdupes -r /path/to/check
Analyze disk usage by file type
find / -type f -exec du -h {} + 2>/dev/null | \
sed 's/.*\.//' | sort | uniq -c | sort -nr | head -20
```
Conclusion
Monitoring disk space in Linux is a fundamental skill for system administrators, developers, and power users. The commands and techniques covered in this guide provide a comprehensive toolkit for managing disk space effectively:
- Use `df -h` for quick filesystem overview
- Use `du -sh` for directory-specific analysis
- Implement automated monitoring for proactive management
- Utilize GUI tools for visual analysis when available
- Follow best practices for regular maintenance
Regular disk space monitoring prevents system issues, maintains performance, and ensures your Linux systems run smoothly. Start with basic commands like `df` and `du`, then gradually incorporate more advanced techniques as needed.
Remember that disk space management is not just about checking usageāit's about developing a systematic approach to monitor, analyze, and maintain your filesystem health. With the tools and knowledge from this guide, you're well-equipped to handle disk space management in any Linux environment.
Whether you're managing a single desktop or multiple servers, these techniques will help you stay ahead of disk space issues and maintain optimal system performance.