Complete Guide to df Command: Check Linux Disk Space

Master the df command to monitor filesystem disk space usage on Linux and Unix systems. Learn syntax, options, and practical examples for system administration.

Complete Guide to Checking Free Disk Space with df Command

Table of Contents

1. [Introduction](#introduction) 2. [Basic Syntax and Usage](#basic-syntax-and-usage) 3. [Command Options and Parameters](#command-options-and-parameters) 4. [Understanding df Output](#understanding-df-output) 5. [Practical Examples](#practical-examples) 6. [Advanced Usage Scenarios](#advanced-usage-scenarios) 7. [Troubleshooting and Best Practices](#troubleshooting-and-best-practices) 8. [Alternative Tools and Comparisons](#alternative-tools-and-comparisons) 9. [System Administration Applications](#system-administration-applications)

Introduction

The df command, short for "disk free" or "disk filesystem," is a fundamental Unix and Linux utility used to display information about filesystem disk space usage. This command provides essential information about mounted filesystems, including total space, used space, available space, and usage percentage. Understanding how to effectively use df is crucial for system administrators, developers, and users who need to monitor disk space and prevent storage-related issues.

The df command operates by reading filesystem statistics from the kernel and presenting them in a human-readable format. It examines mounted filesystems and provides real-time information about their current state, making it an indispensable tool for system monitoring and maintenance.

Basic Syntax and Usage

Command Structure

`bash df [OPTION]... [FILE]... `

The basic syntax consists of the command name followed by optional parameters and target specifications. When executed without arguments, df displays information for all currently mounted filesystems.

Simple Usage Examples

`bash

Display all mounted filesystems

df

Display information for specific filesystem

df /home

Display information for current directory

df . `

Command Options and Parameters

Essential Options Table

| Option | Long Form | Description | Example | |--------|-----------|-------------|---------| | -h | --human-readable | Display sizes in human-readable format | df -h | | -H | --si | Use powers of 1000 instead of 1024 | df -H | | -T | --print-type | Show filesystem type | df -T | | -i | --inodes | Display inode information | df -i | | -a | --all | Include dummy filesystems | df -a | | -l | --local | Limit to local filesystems | df -l | | -x | --exclude-type | Exclude specific filesystem types | df -x tmpfs | | -t | --type | Show only specific filesystem types | df -t ext4 | | -B | --block-size | Set block size | df -B 1M | | --total | --total | Display grand total | df --total |

Detailed Option Explanations

#### Human-Readable Format (-h) The -h option converts raw byte values into more understandable units using binary prefixes (1024-based): - K for kilobytes (1024 bytes) - M for megabytes (1024 KB) - G for gigabytes (1024 MB) - T for terabytes (1024 GB)

`bash df -h

Output shows sizes like 15G, 2.3M, 458K instead of raw numbers

`

#### SI Units (-H) The -H option uses decimal prefixes (1000-based) following the International System of Units: - k for kilobytes (1000 bytes) - M for megabytes (1000 KB) - G for gigabytes (1000 MB) - T for terabytes (1000 GB)

`bash df -H

Output uses decimal calculations for size representation

`

#### Filesystem Type (-T) The -T option adds a column showing the filesystem type for each mounted filesystem:

`bash df -T

Shows ext4, xfs, tmpfs, proc, sysfs, etc.

`

#### Inode Information (-i) The -i option displays inode usage instead of block usage:

`bash df -i

Shows inode counts: total, used, available, and percentage

`

Understanding df Output

Standard Output Format

When executing df without options, the output contains six columns:

| Column | Description | Example Value | |--------|-------------|---------------| | Filesystem | Device name or mount source | /dev/sda1 | | 1K-blocks | Total space in 1K blocks | 20642428 | | Used | Used space in 1K blocks | 10245760 | | Available | Available space in 1K blocks | 9340668 | | Use% | Percentage of space used | 53% | | Mounted on | Mount point directory | / |

Human-Readable Output Format

With the -h option, the output becomes more user-friendly:

`bash $ df -h Filesystem Size Used Avail Use% Mounted on /dev/sda1 20G 10G 8.9G 53% / /dev/sda2 100G 45G 50G 48% /home tmpfs 2.0G 0 2.0G 0% /dev/shm `

Extended Output with Type Information

Using -hT combines human-readable format with filesystem type:

`bash $ df -hT Filesystem Type Size Used Avail Use% Mounted on /dev/sda1 ext4 20G 10G 8.9G 53% / /dev/sda2 ext4 100G 45G 50G 48% /home tmpfs tmpfs 2.0G 0 2.0G 0% /dev/shm proc proc 0 0 0 - /proc sysfs sysfs 0 0 0 - /sys `

Practical Examples

Basic Monitoring Commands

#### Check Overall System Disk Usage `bash df -h ` This command provides a comprehensive overview of all mounted filesystems with human-readable sizes.

#### Monitor Specific Directory `bash df -h /var/log ` Shows disk usage for the filesystem containing the /var/log directory.

#### Check Root Filesystem Only `bash df -h / ` Displays information specifically for the root filesystem.

Advanced Monitoring Examples

#### Monitor Multiple Directories `bash df -h / /home /var /tmp ` Checks disk usage for multiple specific mount points simultaneously.

#### Exclude Temporary Filesystems `bash df -h -x tmpfs -x devtmpfs -x proc -x sysfs ` Shows only physical storage filesystems, excluding virtual and temporary filesystems.

#### Display Only Local Filesystems `bash df -hl ` Excludes network-mounted filesystems, showing only local storage.

#### Show Inode Usage `bash df -hi ` Displays inode usage instead of block usage, useful for identifying directories with many small files.

Scripting and Automation Examples

#### Check Disk Usage Threshold `bash #!/bin/bash THRESHOLD=80 df -h | awk 'NR>1 {print $5 " " $6}' | while read output; do usage=$(echo $output | awk '{print $1}' | sed 's/%//') partition=$(echo $output | awk '{print $2}') if [ $usage -ge $THRESHOLD ]; then echo "Warning: $partition is ${usage}% full" fi done `

#### Generate Disk Usage Report `bash #!/bin/bash echo "Disk Usage Report - $(date)" echo "================================" df -h --total | grep -E "(Filesystem|total|/dev/)" `

Advanced Usage Scenarios

Filesystem Type Filtering

#### Show Only Specific Filesystem Types `bash

Show only ext4 filesystems

df -t ext4 -h

Show only network filesystems

df -t nfs -t cifs -h `

#### Exclude Specific Filesystem Types `bash

Exclude all virtual filesystems

df -x tmpfs -x devtmpfs -x proc -x sysfs -x debugfs -h `

Block Size Customization

#### Custom Block Sizes `bash

Display in megabytes

df -BM

Display in gigabytes

df -BG

Display in specific byte counts

df -B 4096 `

Comprehensive System Analysis

#### Complete Filesystem Overview `bash df -hT --total | column -t ` This command provides a well-formatted complete overview including filesystem types and totals.

#### Detailed Inode Analysis `bash df -i | awk 'NR==1 {print $0} NR>1 && $5+0 > 80 {print $0}' ` Shows filesystems with inode usage above 80%.

Troubleshooting and Best Practices

Common Issues and Solutions

#### Discrepancy Between df and du Sometimes df and du show different values for the same filesystem. This typically occurs due to:

1. Deleted files still held open by processes `bash # Find processes holding deleted files lsof | grep deleted `

2. Reserved space for root user `bash # Check reserved space (typically 5% on ext filesystems) tune2fs -l /dev/sda1 | grep "Reserved block count" `

#### Filesystem Showing 100% Usage When a filesystem shows 100% usage:

`bash

Check for large files

find /path/to/filesystem -type f -size +100M -exec ls -lh {} \;

Check for directories with many files

find /path/to/filesystem -type d -exec sh -c 'echo "$(ls -1 "$1" | wc -l) $1"' _ {} \; | sort -nr | head -10 `

Best Practices Table

| Practice | Description | Command Example | |----------|-------------|-----------------| | Regular monitoring | Check disk usage regularly | df -h | | Set up alerts | Create scripts for threshold monitoring | Custom scripts with cron | | Monitor inodes | Check inode usage for filesystems with many small files | df -i | | Exclude virtual filesystems | Focus on physical storage when monitoring | df -x tmpfs -x proc | | Use human-readable format | Always use -h for better readability | df -h | | Include filesystem types | Add -T to understand filesystem characteristics | df -hT |

Performance Considerations

#### Optimizing df Performance For systems with many mounted filesystems, consider:

`bash

Limit to local filesystems only

df -hl

Use timeout for network filesystems

timeout 10 df -h

Cache results for frequent monitoring

df -h > /tmp/df_cache.txt `

Alternative Tools and Comparisons

Comparison Table of Disk Space Tools

| Tool | Purpose | Advantages | Disadvantages | Best Use Case | |------|---------|------------|---------------|---------------| | df | Filesystem space | Fast, standard, comprehensive | Limited directory detail | System-wide monitoring | | du | Directory usage | Detailed directory breakdown | Slower on large directories | Directory analysis | | lsblk | Block device info | Shows device hierarchy | No usage statistics | Device structure | | fdisk | Partition management | Partition details | Requires root access | Partition analysis | | ncdu | Interactive disk usage | User-friendly interface | Requires installation | Interactive exploration |

Tool Usage Examples

#### Using du for Directory Analysis `bash

Compare with df

df -h /home du -sh /home/* `

#### Using lsblk for Device Structure `bash

Show block device tree

lsblk -f `

#### Combining Tools for Comprehensive Analysis `bash #!/bin/bash echo "=== Filesystem Overview ===" df -hT --total

echo -e "\n=== Block Device Structure ===" lsblk -f

echo -e "\n=== Largest Directories ===" du -sh /* 2>/dev/null | sort -hr | head -10 `

System Administration Applications

Monitoring Scripts

#### Daily Disk Usage Report `bash #!/bin/bash

daily_disk_report.sh

LOGFILE="/var/log/disk_usage.log" DATE=$(date '+%Y-%m-%d %H:%M:%S')

echo "[$DATE] Daily Disk Usage Report" >> $LOGFILE df -h --total >> $LOGFILE echo "----------------------------------------" >> $LOGFILE

Send email if any filesystem is above 90%

CRITICAL=$(df -h | awk 'NR>1 {gsub(/%/,"",$5); if($5 > 90) print $6 " is " $5 "% full"}') if [ ! -z "$CRITICAL" ]; then echo "$CRITICAL" | mail -s "Critical Disk Usage Alert" admin@example.com fi `

#### Real-time Monitoring `bash #!/bin/bash

realtime_disk_monitor.sh

while true; do clear echo "Real-time Disk Usage Monitor - $(date)" echo "=======================================" df -h --total | grep -E "(Filesystem|/dev/|total)" echo "" echo "Press Ctrl+C to exit" sleep 30 done `

Capacity Planning

#### Historical Usage Tracking `bash #!/bin/bash

track_usage.sh

DATAFILE="/var/log/disk_history.csv"

Create header if file doesn't exist

if [ ! -f "$DATAFILE" ]; then echo "Date,Filesystem,Size,Used,Available,Use%" > $DATAFILE fi

Record current usage

df -h | grep "^/dev/" | while read line; do DATE=$(date '+%Y-%m-%d') echo "$DATE,$line" >> $DATAFILE done `

#### Growth Prediction Script `bash #!/bin/bash

predict_growth.sh

FILESYSTEM="/" DAYS=30

echo "Analyzing $FILESYSTEM growth over last $DAYS days..."

Extract usage data and calculate trend

tail -n $DAYS /var/log/disk_history.csv | grep "$FILESYSTEM" | \ awk -F',' '{gsub(/%/,"",$6); print NR, $6}' | \ awk '{sum+=$2; sumsq+=$2*$2; n++} END { mean=sum/n; slope=(nsum_xy - sumsum_y)/(nsum_xx - sumsum); print "Average usage:", mean "%"; print "Daily growth rate:", slope "%/day"; print "Estimated full in:", (100-mean)/slope, "days" }' `

Automated Maintenance

#### Cleanup Script Based on df Output `bash #!/bin/bash

auto_cleanup.sh

THRESHOLD=85

Check each filesystem

df -h | grep "^/dev/" | while read line; do USAGE=$(echo $line | awk '{gsub(/%/,"",$5); print $5}') MOUNT=$(echo $line | awk '{print $6}') if [ $USAGE -gt $THRESHOLD ]; then echo "Cleaning up $MOUNT (${USAGE}% full)" # Clean temporary files find $MOUNT -name "*.tmp" -type f -mtime +7 -delete 2>/dev/null # Clean old log files find $MOUNT -name "*.log" -type f -mtime +30 -delete 2>/dev/null # Report new usage NEW_USAGE=$(df -h $MOUNT | tail -1 | awk '{gsub(/%/,"",$5); print $5}') echo "Cleanup complete. Usage now: ${NEW_USAGE}%" fi done `

Integration with System Monitoring

#### Nagios Plugin Example `bash #!/bin/bash

check_disk_space.sh - Nagios plugin

WARNING=80 CRITICAL=90 FILESYSTEM=$1

if [ -z "$FILESYSTEM" ]; then echo "UNKNOWN - Filesystem not specified" exit 3 fi

USAGE=$(df -h "$FILESYSTEM" | tail -1 | awk '{gsub(/%/,"",$5); print $5}')

if [ $USAGE -ge $CRITICAL ]; then echo "CRITICAL - Disk usage ${USAGE}% on $FILESYSTEM" exit 2 elif [ $USAGE -ge $WARNING ]; then echo "WARNING - Disk usage ${USAGE}% on $FILESYSTEM" exit 1 else echo "OK - Disk usage ${USAGE}% on $FILESYSTEM" exit 0 fi `

#### Prometheus Metrics Export `bash #!/bin/bash

disk_metrics.sh - Export disk metrics for Prometheus

echo "# HELP filesystem_size_bytes Total size of filesystem in bytes" echo "# TYPE filesystem_size_bytes gauge"

df -B1 | grep "^/dev/" | while read line; do DEVICE=$(echo $line | awk '{print $1}') SIZE=$(echo $line | awk '{print $2}') USED=$(echo $line | awk '{print $3}') MOUNT=$(echo $line | awk '{print $6}') echo "filesystem_size_bytes{device=\"$DEVICE\",mountpoint=\"$MOUNT\"} $SIZE" echo "filesystem_used_bytes{device=\"$DEVICE\",mountpoint=\"$MOUNT\"} $USED" done `

This comprehensive guide covers all aspects of using the df command for disk space monitoring and management. From basic usage to advanced system administration applications, these examples and explanations provide the foundation for effective disk space management in Unix and Linux environments. Regular monitoring using df combined with automated scripts and proper alerting mechanisms ensures optimal system performance and prevents storage-related issues before they impact system operations.

Tags

  • Command Line
  • Linux
  • Unix
  • filesystem
  • monitoring

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Complete Guide to df Command: Check Linux Disk Space