How to check free disk space with df
How to Check Free Disk Space with df
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites](#prerequisites)
3. [Understanding the df Command](#understanding-the-df-command)
4. [Basic df Command Usage](#basic-df-command-usage)
5. [df Command Options and Flags](#df-command-options-and-flags)
6. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
7. [Advanced df Usage](#advanced-df-usage)
8. [Interpreting df Output](#interpreting-df-output)
9. [Common Issues and Troubleshooting](#common-issues-and-troubleshooting)
10. [Best Practices and Professional Tips](#best-practices-and-professional-tips)
11. [Alternative Commands and Tools](#alternative-commands-and-tools)
12. [Conclusion](#conclusion)
Introduction
The `df` (disk free) command is one of the most fundamental and essential tools in Linux and Unix-like operating systems for monitoring disk space usage. Whether you're a system administrator managing servers, a developer working on local projects, or a casual user maintaining your personal computer, understanding how to check free disk space is crucial for system maintenance and preventing storage-related issues.
This comprehensive guide will teach you everything you need to know about using the `df` command effectively. You'll learn basic usage, advanced options, real-world applications, troubleshooting techniques, and professional best practices that will help you master disk space monitoring in any Linux or Unix environment.
By the end of this article, you'll be able to confidently use the `df` command to monitor disk usage, identify storage issues before they become critical, and implement effective disk space management strategies in your daily workflow.
Prerequisites
Before diving into the `df` command, ensure you have:
- Operating System: Linux, Unix, macOS, or any Unix-like system
- Access Level: Basic user access (some operations may require root privileges)
- Terminal Access: Command-line interface or terminal emulator
- Basic Knowledge: Fundamental understanding of command-line operations
- File System Awareness: Basic understanding of file systems and mount points
System Requirements
The `df` command is pre-installed on virtually all Linux and Unix distributions, including:
- Ubuntu, Debian, and derivatives
- Red Hat Enterprise Linux (RHEL), CentOS, Fedora
- SUSE Linux Enterprise, openSUSE
- Arch Linux, Manjaro
- macOS and other BSD variants
Understanding the df Command
What is df?
The `df` command stands for "disk free" and displays information about file system disk space usage. It shows the amount of disk space used and available on mounted file systems, providing essential information for system monitoring and maintenance.
How df Works
The `df` command reads file system statistics from the kernel and presents them in a human-readable format. It queries each mounted file system to determine:
- Total space available
- Space currently used
- Free space remaining
- Usage percentage
- Mount point location
Key Concepts
File Systems: Storage structures that organize and manage data on storage devices.
Mount Points: Directory locations where file systems are attached to the system's directory tree.
Inodes: Data structures that store metadata about files and directories.
Block Size: The smallest unit of data that can be allocated on a file system.
Basic df Command Usage
Simple df Command
The most basic usage of the `df` command is simply typing `df` in your terminal:
```bash
df
```
This displays disk usage information for all currently mounted file systems. The output typically looks like this:
```
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 20511312 4123456 15234567 22% /
/dev/sda2 51200000 8456789 41234567 18% /home
tmpfs 2048000 0 2048000 0% /tmp
```
Understanding Basic Output
Each line in the output represents a mounted file system with the following columns:
- Filesystem: The device or file system name
- 1K-blocks: Total space in 1024-byte blocks
- Used: Space currently occupied
- Available: Free space remaining
- Use%: Percentage of space used
- Mounted on: Mount point directory
Human-Readable Format
For easier interpretation, use the `-h` (human-readable) flag:
```bash
df -h
```
Output example:
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 20G 4.0G 15G 22% /
/dev/sda2 49G 8.1G 40G 18% /home
tmpfs 2.0G 0 2.0G 0% /tmp
```
df Command Options and Flags
Essential Options
-h, --human-readable
Displays sizes in human-readable format (K, M, G, T):
```bash
df -h
```
-H, --si
Uses powers of 1000 instead of 1024:
```bash
df -H
```
-T, --print-type
Shows file system types:
```bash
df -T
```
Output:
```
Filesystem Type 1K-blocks Used Available Use% Mounted on
/dev/sda1 ext4 20511312 4123456 15234567 22% /
/dev/sda2 ext4 51200000 8456789 41234567 18% /home
tmpfs tmpfs 2048000 0 2048000 0% /tmp
```
-i, --inodes
Displays inode usage instead of block usage:
```bash
df -i
```
-a, --all
Shows all file systems, including pseudo file systems:
```bash
df -a
```
Advanced Options
-x, --exclude-type
Excludes specific file system types:
```bash
df -x tmpfs -x devtmpfs
```
-t, --type
Shows only specific file system types:
```bash
df -t ext4
```
--total
Adds a total line at the bottom:
```bash
df -h --total
```
-l, --local
Displays only local file systems:
```bash
df -l
```
Practical Examples and Use Cases
Example 1: Basic System Monitoring
Check overall disk usage across all mounted file systems:
```bash
df -h
```
Use Case: Daily system health checks to ensure no file systems are approaching capacity.
Example 2: Monitoring Specific Directory
Check disk usage for a specific mount point:
```bash
df -h /home
```
Output:
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 49G 8.1G 40G 18% /home
```
Use Case: Monitoring user directories or application data directories.
Example 3: Comprehensive System Report
Generate a detailed report including file system types:
```bash
df -hT
```
Use Case: System documentation and capacity planning.
Example 4: Inode Usage Monitoring
Check inode usage to identify potential file system issues:
```bash
df -hi
```
Output:
```
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/sda1 1.3M 234K 1.1M 18% /
/dev/sda2 3.2M 456K 2.7M 15% /home
```
Use Case: Troubleshooting "No space left on device" errors when disk space appears available.
Example 5: Excluding Pseudo File Systems
Focus on physical storage devices only:
```bash
df -hx tmpfs -x devtmpfs -x sysfs -x proc
```
Use Case: Clean reporting for capacity planning and storage management.
Example 6: Monitoring with Total Summary
Get an overview with total usage:
```bash
df -h --total
```
Output:
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 20G 4.0G 15G 22% /
/dev/sda2 49G 8.1G 40G 18% /home
total 69G 12G 55G 18% -
```
Use Case: Executive reporting and high-level capacity overview.
Advanced df Usage
Scripting with df
Basic Monitoring Script
```bash
#!/bin/bash
disk_monitor.sh - Simple disk space monitoring
THRESHOLD=80
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 $partition is ${usage}% full"
fi
done
```
Advanced Monitoring with Email Alerts
```bash
#!/bin/bash
advanced_disk_monitor.sh
THRESHOLD=85
EMAIL="admin@example.com"
check_disk_usage() {
df -h | awk 'NR>1 {
usage = substr($5, 1, length($5)-1)
if (usage > '$THRESHOLD') {
print "CRITICAL: " $6 " is " $5 " full (" $3 " used of " $2 ")"
}
}'
}
ALERTS=$(check_disk_usage)
if [ ! -z "$ALERTS" ]; then
echo "$ALERTS" | mail -s "Disk Space Alert" $EMAIL
fi
```
Combining df with Other Commands
Finding Large Files in Full Partitions
```bash
Identify partition usage
df -h
Find large files in a specific directory
find /home -type f -size +100M -exec ls -lh {} \; | sort -k5 -hr
```
Real-time Monitoring
```bash
Monitor disk usage every 5 seconds
watch -n 5 'df -h'
```
Logging Disk Usage
```bash
Log disk usage with timestamp
echo "$(date): $(df -h | grep '/dev/sda1')" >> /var/log/disk_usage.log
```
Interpreting df Output
Understanding Usage Percentages
Low Usage (0-50%): Normal operation range
Medium Usage (51-80%): Monitor closely, plan for expansion
High Usage (81-95%): Take immediate action
Critical Usage (96-100%): Emergency situation requiring immediate intervention
File System Behavior at High Usage
When file systems approach 100% capacity:
- Performance degradation occurs
- System operations may fail
- Log files cannot be written
- Applications may crash
- System instability increases
Reserved Space Considerations
Most Linux file systems reserve 5% of space for root user operations. This means:
- User processes stop writing at 95% usage
- Root can still perform maintenance operations
- The reserved space prevents complete system lockup
Common Issues and Troubleshooting
Issue 1: "No space left on device" with Available Space
Symptom: Error message appears despite `df` showing available space.
Cause: Inode exhaustion
Solution:
```bash
Check inode usage
df -i
Find directories with many small files
find / -type d -exec sh -c 'echo "$(ls -1 "$1" | wc -l) $1"' _ {} \; | sort -nr | head -10
```
Issue 2: Discrepancy Between df and du
Symptom: `df` shows less free space than `du` calculations suggest.
Cause: Deleted files still held open by processes
Solution:
```bash
Find processes with deleted files
lsof +L1
Restart services holding deleted files
systemctl restart service_name
```
Issue 3: Sudden Space Disappearance
Symptom: Available space decreases rapidly without apparent cause.
Diagnosis Steps:
```bash
Check for large files created recently
find / -type f -mtime -1 -size +100M 2>/dev/null
Monitor real-time file system changes
inotifywatch -r /path/to/monitor
Check for core dumps
find / -name "core.*" -type f -size +10M 2>/dev/null
```
Issue 4: Mount Point Issues
Symptom: `df` shows unexpected file systems or missing mount points.
Solution:
```bash
Check mount status
mount | grep -E '^/dev'
Verify /etc/fstab configuration
cat /etc/fstab
Check for mount point overlay issues
findmnt -D
```
Issue 5: Permission Denied Errors
Symptom: `df` cannot access certain file systems.
Solution:
```bash
Run with elevated privileges
sudo df -h
Check file system permissions
ls -la /mnt/
Verify mount point accessibility
stat /mount/point
```
Best Practices and Professional Tips
Monitoring Best Practices
1. Regular Monitoring Schedule
```bash
Add to crontab for daily monitoring
0 8 * /usr/local/bin/disk_monitor.sh
Weekly detailed reports
0 9 1 df -h --total | mail -s "Weekly Disk Usage Report" admin@domain.com
```
2. Threshold Management
- Set warning thresholds at 80%
- Set critical thresholds at 90%
- Plan capacity expansion at 75%
3. Documentation Standards
```bash
Create standardized reporting format
df -hT | grep -E '^/dev' > /var/log/disk_usage_$(date +%Y%m%d).log
```
Performance Optimization Tips
1. Efficient Command Usage
```bash
For scripts, use specific options to reduce overhead
df -P /specific/path # POSIX format for parsing
Avoid unnecessary options in automated scripts
df --output=source,size,used,avail,pcent,target
```
2. Filtering Techniques
```bash
Exclude pseudo file systems efficiently
df -hx tmpfs -x devtmpfs -x sysfs
Focus on specific file system types
df -t ext4 -t xfs
```
Security Considerations
1. Information Disclosure
- Be cautious when sharing `df` output externally
- Sensitive mount points may reveal system architecture
- Use filtering for public reports
2. Access Control
```bash
Create restricted monitoring user
useradd -r -s /bin/false diskmon
Grant specific sudo privileges
diskmon ALL=(root) NOPASSWD: /bin/df
```
Integration with Monitoring Systems
1. Nagios Integration
```bash
#!/bin/bash
nagios_disk_check.sh
CRITICAL=90
WARNING=80
USAGE=$(df -h / | awk 'NR==2 {print substr($5,1,length($5)-1)}')
if [ $USAGE -ge $CRITICAL ]; then
echo "CRITICAL - Disk usage ${USAGE}%"
exit 2
elif [ $USAGE -ge $WARNING ]; then
echo "WARNING - Disk usage ${USAGE}%"
exit 1
else
echo "OK - Disk usage ${USAGE}%"
exit 0
fi
```
2. Prometheus Metrics
```bash
Export df metrics for Prometheus
df -P | awk 'NR>1 {
gsub(/[^a-zA-Z0-9_]/, "_", $6)
print "disk_total_bytes{mountpoint=\"" $6 "\"} " $2*1024
print "disk_used_bytes{mountpoint=\"" $6 "\"} " $3*1024
print "disk_free_bytes{mountpoint=\"" $6 "\"} " $4*1024
}'
```
Alternative Commands and Tools
Related Commands
du - Disk Usage
```bash
Show directory usage
du -sh /home/*
Find largest directories
du -h / | sort -hr | head -20
```
lsblk - List Block Devices
```bash
Show block device tree
lsblk -f
Include file system information
lsblk -fs
```
findmnt - Find Mount Points
```bash
Show mount tree
findmnt
Verify specific mount
findmnt /home
```
Modern Alternatives
ncdu - Interactive Disk Usage
```bash
Install and run interactive analyzer
sudo apt install ncdu
ncdu /
```
duf - Modern df Alternative
```bash
More colorful and informative output
duf
```
Conclusion
The `df` command is an indispensable tool for system administration and disk space management in Linux and Unix environments. Throughout this comprehensive guide, we've explored everything from basic usage to advanced scripting techniques, troubleshooting methods, and professional best practices.
Key Takeaways
1. Essential Knowledge: Understanding `df` output is crucial for system health monitoring
2. Proactive Monitoring: Regular disk space checks prevent critical system issues
3. Proper Usage: Using appropriate flags and options provides more meaningful information
4. Scripting Integration: Automating disk space monitoring improves system reliability
5. Troubleshooting Skills: Knowing how to diagnose disk-related issues saves valuable time
Next Steps
To further enhance your disk management skills:
1. Implement Monitoring: Set up automated disk space monitoring in your environment
2. Practice Scripting: Create custom monitoring scripts tailored to your needs
3. Explore Integration: Connect disk monitoring with your existing monitoring infrastructure
4. Learn Complementary Tools: Master related commands like `du`, `lsblk`, and `findmnt`
5. Develop Procedures: Create standard operating procedures for disk space management
Final Recommendations
- Always monitor disk space proactively rather than reactively
- Understand your file system's behavior at high utilization
- Implement proper alerting thresholds based on your environment's needs
- Document your disk monitoring procedures for team consistency
- Regular practice with `df` and related commands builds confidence and expertise
By mastering the `df` command and implementing the practices outlined in this guide, you'll be well-equipped to maintain healthy storage systems and prevent disk space-related issues in any Linux or Unix environment. Remember that effective disk space management is not just about knowing the commands—it's about developing good habits, implementing proper monitoring, and responding appropriately to the information these tools provide.