How to check disk free space → df
How to Check Disk Free Space → df
Table of Contents
- [Introduction](#introduction)
- [Prerequisites](#prerequisites)
- [Understanding the df Command](#understanding-the-df-command)
- [Basic df Command Usage](#basic-df-command-usage)
- [df Command Options and Flags](#df-command-options-and-flags)
- [Practical Examples and Use Cases](#practical-examples-and-use-cases)
- [Reading and Interpreting df Output](#reading-and-interpreting-df-output)
- [Advanced df Usage](#advanced-df-usage)
- [Common Issues and Troubleshooting](#common-issues-and-troubleshooting)
- [Best Practices and Professional Tips](#best-practices-and-professional-tips)
- [Alternative Commands and Tools](#alternative-commands-and-tools)
- [Automation and Scripting](#automation-and-scripting)
- [Conclusion](#conclusion)
Introduction
Monitoring disk space is one of the most fundamental tasks in system administration and daily computer maintenance. Running out of disk space can cause system crashes, application failures, and data loss. The `df` (disk free) command is a powerful and essential Unix/Linux utility that displays information about file system disk space usage on mounted file systems.
In this comprehensive guide, you'll learn everything you need to know about using the `df` command effectively. Whether you're a beginner just starting with Linux or an experienced system administrator looking to refine your skills, this article covers basic usage, advanced options, practical examples, troubleshooting techniques, and professional best practices.
By the end of this guide, you'll be able to confidently check disk space, interpret the output, identify potential storage issues, and implement monitoring solutions using the `df` command across various Unix-like operating systems including Linux, macOS, and BSD variants.
Prerequisites
Before diving into the `df` command, ensure you have:
System Requirements
- Access to a Unix-like operating system (Linux, macOS, FreeBSD, etc.)
- Terminal or command-line interface access
- Basic familiarity with command-line navigation
Knowledge Prerequisites
- Understanding of basic terminal commands
- Familiarity with file system concepts
- Basic knowledge of directory structures and paths
Access Requirements
- User-level access (most df operations don't require root privileges)
- For some advanced operations, sudo or root access may be needed
Understanding the df Command
What is df?
The `df` command stands for "disk free" and is a standard Unix command used to display the amount of disk space used and available on file systems. It reads information from the kernel's file system statistics and presents it in a human-readable format.
How df Works
When you execute the `df` command, it:
1. Queries the kernel for file system information
2. Retrieves data about mounted file systems
3. Calculates used and available space
4. Displays the information in tabular format
Key Concepts
File System: A method of organizing and storing files on storage devices.
Mount Point: A directory where a file system is attached to the directory tree.
Blocks: The basic unit of storage allocation, typically measured in 1K blocks by default.
Inodes: Data structures that store information about files and directories.
Basic df Command Usage
Simple df Command
The most basic usage of the `df` command is simply typing:
```bash
df
```
This displays disk space information for all currently mounted file systems. The output typically looks like this:
```
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 20511312 4523456 14912504 24% /
/dev/sda2 51475068 2048576 46951140 5% /home
tmpfs 2048000 12345 2035655 1% /tmp
```
Understanding Basic Output Columns
- Filesystem: The device or file system name
- 1K-blocks: Total size in 1024-byte blocks
- Used: Space currently used
- Available: Space available for use
- Use%: Percentage of space used
- Mounted on: Mount point directory
Human-Readable Format
For easier reading, use the `-h` (human-readable) option:
```bash
df -h
```
Output example:
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 20G 4.4G 15G 24% /
/dev/sda2 50G 2.0G 46G 5% /home
tmpfs 2.0G 12M 2.0G 1% /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
```
-k
Shows output in 1K blocks (default):
```bash
df -k
```
-m
Displays output in megabytes:
```bash
df -m
```
-T, --print-type
Shows file system type:
```bash
df -T
```
Output example:
```
Filesystem Type 1K-blocks Used Available Use% Mounted on
/dev/sda1 ext4 20511312 4523456 14912504 24% /
/dev/sda2 ext4 51475068 2048576 46951140 5% /home
```
Advanced Options
-i, --inodes
Displays inode usage instead of block usage:
```bash
df -i
```
-a, --all
Shows all file systems, including those with 0 blocks:
```bash
df -a
```
-l, --local
Limits listing to local file systems:
```bash
df -l
```
-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
```
Practical Examples and Use Cases
Example 1: Quick System Overview
Check overall system disk usage:
```bash
df -h
```
This provides a quick overview of all mounted file systems with human-readable sizes.
Example 2: Specific Directory Check
Check disk space for a specific directory:
```bash
df -h /home
```
Output:
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 50G 2.0G 46G 5% /home
```
Example 3: Multiple Directories
Check multiple specific paths:
```bash
df -h / /home /var
```
Example 4: File System Type Analysis
View file systems with their types:
```bash
df -hT
```
Output:
```
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda1 ext4 20G 4.4G 15G 24% /
/dev/sda2 ext4 50G 2.0G 46G 5% /home
tmpfs tmpfs 2.0G 12M 2.0G 1% /tmp
```
Example 5: 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 145K 1.2M 11% /
/dev/sda2 3.3M 52K 3.2M 2% /home
```
Example 6: Excluding System File Systems
Show only relevant file systems by excluding temporary and system mounts:
```bash
df -h -x tmpfs -x devtmpfs -x squashfs
```
Reading and Interpreting df Output
Understanding Usage Percentages
Green Zone (0-70%): Normal usage levels
- System operates efficiently
- Adequate space for normal operations
- No immediate action required
Yellow Zone (70-90%): Caution required
- Monitor usage trends
- Consider cleanup or expansion
- Plan for future storage needs
Red Zone (90-100%): Critical attention needed
- Immediate action required
- System performance may degrade
- Risk of application failures
Analyzing Available Space
When interpreting available space:
```bash
df -h /
```
Output analysis:
```
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 20G 18G 1.2G 94% /
```
Critical indicators:
- Use%: 94% indicates critical usage
- Avail: Only 1.2G remaining
- Action needed: Immediate cleanup or expansion
Reserved Space Considerations
Most file systems reserve 5% of space for root user:
- Prevents complete disk filling
- Ensures system stability
- May cause discrepancies in calculations
Calculate reserved space:
```bash
If total shows 20G but Used + Avail = 19G
Reserved space = 20G - 19G = 1G (5%)
```
Advanced df Usage
Combining with Other Commands
Sort by Usage Percentage
```bash
df -h | sort -k5 -nr
```
Find Largest Partitions
```bash
df -h | sort -k2 -hr
```
Filter High Usage
```bash
df -h | awk '$5 > 80 {print $0}'
```
Using df with grep
Filter specific mount points:
```bash
df -h | grep -E "^/dev"
```
Show only high usage file systems:
```bash
df -h | grep -E "9[0-9]%|100%"
```
Custom Output Formatting
Create custom output with specific columns:
```bash
df -h --output=source,pcent,target
```
Available output fields:
- source: File system source
- fstype: File system type
- itotal: Total inodes
- iused: Used inodes
- iavail: Available inodes
- ipcent: Percentage of inodes used
- size: Total size
- used: Used space
- avail: Available space
- pcent: Percentage used
- file: File name if specified
- target: Mount point
Common Issues and Troubleshooting
Issue 1: Command Not Found
Problem: `df: command not found`
Solution:
```bash
Check if df is in PATH
which df
Common locations
ls -l /bin/df
ls -l /usr/bin/df
If missing, reinstall coreutils (Linux)
sudo apt-get install coreutils # Debian/Ubuntu
sudo yum install coreutils # CentOS/RHEL
```
Issue 2: Permission Denied
Problem: Cannot access certain file systems
Solution:
```bash
Use sudo for system file systems
sudo df -h
Check mount permissions
mount | grep "permission denied"
```
Issue 3: Stale NFS Mounts
Problem: df hangs on network file systems
Solution:
```bash
Use local file systems only
df -l
Force unmount stale NFS
sudo umount -f /mnt/nfs_mount
Or use lazy unmount
sudo umount -l /mnt/nfs_mount
```
Issue 4: Discrepancy Between df and du
Problem: `df` and `du` show different space usage
Causes and Solutions:
1. Open file handles to deleted files:
```bash
Find processes with deleted file handles
lsof +L1
Restart services holding deleted files
sudo systemctl restart service_name
```
2. Different calculation methods:
```bash
df shows file system level
df -h /
du shows directory level
du -sh /
```
3. Reserved space:
```bash
Check reserved blocks
tune2fs -l /dev/sda1 | grep "Reserved block count"
```
Issue 5: 100% Full but Files Can Still be Created
Problem: File system shows 100% but root can create files
Explanation: Reserved space for root user
```bash
Check reserved space
tune2fs -l /dev/sda1 | grep -i reserved
Modify reserved space (careful!)
sudo tune2fs -r 0 /dev/sda1 # Remove reserved space
```
Best Practices and Professional Tips
Monitoring Best Practices
1. Regular Monitoring Schedule
```bash
Daily check script
#!/bin/bash
df -h | awk '$5 > 80 {print "WARNING: " $0}' | mail -s "Disk Usage Alert" admin@company.com
```
2. Threshold-Based Alerting
```bash
#!/bin/bash
THRESHOLD=85
df -h | awk -v threshold=$THRESHOLD '
$5 > threshold {
gsub(/%/, "", $5);
print "ALERT: " $6 " is " $5 "% full"
}'
```
3. Historical Tracking
```bash
Log disk usage trends
echo "$(date): $(df -h /)" >> /var/log/disk-usage.log
```
Performance Considerations
1. Avoid Frequent Polling
- Don't run df every second in scripts
- Use appropriate intervals (5-15 minutes)
- Consider system load impact
2. Network File Systems
```bash
Use timeout for network mounts
timeout 10 df -h /mnt/network_mount
```
3. Large File Systems
```bash
For very large file systems, consider
df -h --total # Shows grand total
```
Security Considerations
1. Information Disclosure
- df output reveals system structure
- Consider access restrictions in shared environments
- Filter sensitive mount points in scripts
2. Privilege Escalation
- Some mount points require elevated privileges
- Use principle of least privilege
- Validate input in automated scripts
Integration with Monitoring Systems
Nagios Plugin Example
```bash
#!/bin/bash
check_disk_space.sh
WARN_THRESHOLD=80
CRIT_THRESHOLD=90
USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $USAGE -ge $CRIT_THRESHOLD ]; then
echo "CRITICAL: Disk usage is ${USAGE}%"
exit 2
elif [ $USAGE -ge $WARN_THRESHOLD ]; then
echo "WARNING: Disk usage is ${USAGE}%"
exit 1
else
echo "OK: Disk usage is ${USAGE}%"
exit 0
fi
```
Prometheus Integration
```bash
Export metrics for Prometheus
df -h | awk 'NR>1 {
gsub(/%/, "", $5);
print "disk_usage_percent{mount=\"" $6 "\"} " $5
}'
```
Alternative Commands and Tools
du Command
For directory-level analysis:
```bash
Check directory sizes
du -sh /var/log/*
Find largest directories
du -h / 2>/dev/null | sort -hr | head -10
```
lsblk Command
For block device information:
```bash
Show block device tree
lsblk
Show file systems
lsblk -f
```
ncdu (NCurses Disk Usage)
Interactive disk usage analyzer:
```bash
Install ncdu
sudo apt-get install ncdu
Analyze directory
ncdu /home
```
pydf (Python df)
Enhanced df with colors and bars:
```bash
Install pydf
pip install pydf
Run with colors
pydf
```
Automation and Scripting
Disk Space Monitoring Script
```bash
#!/bin/bash
disk_monitor.sh - Comprehensive disk monitoring
Configuration
WARN_THRESHOLD=80
CRIT_THRESHOLD=90
EMAIL="admin@company.com"
LOG_FILE="/var/log/disk-monitor.log"
Function to log messages
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" >> "$LOG_FILE"
}
Function to send alert
send_alert() {
local severity=$1
local message=$2
echo "$message" | mail -s "[$severity] Disk Space Alert" "$EMAIL"
log_message "$severity: $message"
}
Main monitoring loop
check_disk_space() {
df -h | awk -v warn=$WARN_THRESHOLD -v crit=$CRIT_THRESHOLD '
NR > 1 && $5 != "-" {
usage = $5
gsub(/%/, "", usage)
if (usage >= crit) {
print "CRITICAL: " $6 " is " $5 " full (" $4 " available)"
} else if (usage >= warn) {
print "WARNING: " $6 " is " $5 " full (" $4 " available)"
}
}' | while read line; do
if [[ $line == CRITICAL* ]]; then
send_alert "CRITICAL" "$line"
elif [[ $line == WARNING* ]]; then
send_alert "WARNING" "$line"
fi
done
}
Run the check
check_disk_space
Log successful completion
log_message "Disk space check completed successfully"
```
Cron Job Setup
Add to crontab for automated monitoring:
```bash
Edit crontab
crontab -e
Add monitoring job (every 15 minutes)
/15 * /usr/local/bin/disk_monitor.sh
Daily summary report
0 9 * df -h | mail -s "Daily Disk Usage Report" admin@company.com
```
JSON Output Script
For integration with modern monitoring systems:
```bash
#!/bin/bash
df_json.sh - Output df information as JSON
df -h --output=source,fstype,size,used,avail,pcent,target | \
awk 'BEGIN {print "{"}
NR==1 {next}
NR>2 {print ","}
{
gsub(/%/, "", $6)
printf " \"%s\": {\"type\":\"%s\", \"size\":\"%s\", \"used\":\"%s\", \"available\":\"%s\", \"usage\":%d, \"mount\":\"%s\"}",
$1, $2, $3, $4, $5, $6, $7
}
END {print "\n}"}'
```
Conclusion
The `df` command is an indispensable tool for system administrators, developers, and anyone managing Unix-like systems. Throughout this comprehensive guide, we've explored everything from basic usage to advanced automation techniques.
Key Takeaways
1. Essential Monitoring: Regular disk space monitoring prevents system failures and ensures optimal performance.
2. Versatile Options: The df command offers numerous options for different use cases, from simple checks to detailed analysis.
3. Integration Capabilities: df works seamlessly with other Unix tools and can be integrated into comprehensive monitoring solutions.
4. Troubleshooting Skills: Understanding common issues and their solutions helps maintain system reliability.
5. Automation Benefits: Automated monitoring and alerting systems provide proactive system management.
Next Steps
To further enhance your system administration skills:
1. Practice Regularly: Use df commands in your daily workflow to build familiarity
2. Create Monitoring Scripts: Develop custom monitoring solutions for your specific needs
3. Explore Related Tools: Learn complementary commands like du, lsblk, and ncdu
4. Implement Alerting: Set up proactive monitoring and alerting systems
5. Study File Systems: Deepen your understanding of different file system types and their characteristics
Final Recommendations
- Always monitor disk space proactively rather than reactively
- Implement multiple layers of monitoring (command-line, scripts, and enterprise tools)
- Document your monitoring procedures and thresholds
- Regularly review and update your monitoring strategies
- Keep learning about new tools and techniques in system administration
By mastering the df command and implementing the practices outlined in this guide, you'll be well-equipped to maintain healthy, well-monitored systems that avoid the common pitfalls of disk space management. Remember that effective system administration is about prevention, monitoring, and having the right tools and knowledge to respond quickly when issues arise.
The df command, while simple in concept, is a powerful foundation for robust system monitoring and management. Use it wisely, and it will serve you well throughout your journey in system administration and beyond.