Commands

Df Command on Linux with Examples

Df Command on Linux

The Linux operating system provides numerous command-line utilities that help users and system administrators efficiently manage their systems. Among these utilities, the df command stands out as an essential tool for monitoring disk space usage. Whether you’re a seasoned Linux administrator or a newcomer to the Linux environment, understanding how to use the df command effectively can significantly enhance your system management capabilities. This comprehensive guide explores the df command in detail, providing practical examples, troubleshooting tips, and best practices to help you master this fundamental Linux utility.

Table of Contents

Introduction to the Df Command

The df command, which stands for “Disk Filesystem,” is a standard Linux utility designed to report file system disk space usage. It provides critical information about mounted filesystems, including their total size, used space, available space, and mount points. System administrators rely on this command daily to ensure systems have adequate disk space and to prevent potential issues that might arise from disk space shortages.

The primary purpose of df is straightforward: it reports how much disk space is available on the filesystem containing each file name argument. When no file name is given, it shows available space on all currently mounted filesystems. This simple yet powerful functionality makes df an indispensable tool in the Linux environment.

For both novice users and experienced system administrators, the df command serves as a first line of defense against disk space issues. Regular monitoring with df helps prevent system crashes, application failures, and data loss that might occur when filesystems reach capacity. Its simplicity and efficiency make it one of the most frequently used commands in Linux system maintenance.

Understanding the Basics of Df Command

At its core, the df command queries the kernel’s file system statistics to report available disk space on mounted filesystems. Unlike some more complex utilities, df provides a clear, concise overview of your disk usage situation with minimal processing overhead.

When executed without any options, df displays information in a tabular format with several columns, including the filesystem device, total blocks, used blocks, available blocks, usage percentage, and mount point. By default, df reports space in 1K blocks, which might not be the most human-friendly format, but it provides precision for system-level operations.

$ df
Filesystem     1K-blocks     Used Available Use% Mounted on
udev             4046836        0   4046836   0% /dev
tmpfs             814200     1852    812348   1% /run
/dev/sda1       97605056 68694600  23864072  75% /
tmpfs            4071004    12944   4058060   1% /dev/shm

The df command differs from other disk utilities like du (disk usage) in that df examines the filesystem superblocks to gather information, while du recursively traverses directories to calculate disk usage. This difference means df operates much faster, especially on large filesystems, but sometimes shows results that appear inconsistent with du output due to their different approaches to measurement.

You’ll find df particularly useful in scenarios where you need a quick overview of available space across all filesystems, when investigating disk space alerts, or when planning capacity upgrades. It’s typically the first command to reach for when users report “disk full” errors or when applications fail due to storage constraints.

Command Syntax and Structure

The basic syntax of the df command follows this pattern:

df [OPTION]... [FILE]...

When run without any options or arguments, df reports information about all mounted filesystems. If you specify a file or directory as an argument, df reports on the filesystem containing that file or directory.

The default output columns include:

  1. Filesystem: The device name or filesystem identifier
  2. 1K-blocks: Total size in 1-kilobyte blocks
  3. Used: Space used in 1-kilobyte blocks
  4. Available: Available space in 1-kilobyte blocks
  5. Use%: Percentage of space used
  6. Mounted on: Mount point of the filesystem

Interpreting these results is straightforward. The “Use%” column provides a quick visual indication of how full each filesystem is, while the “Available” column shows the remaining space in blocks.

In terms of permissions, the df command is accessible to all users since it only reads filesystem information. However, some specific filesystems might only show complete information to the root user or users with appropriate permissions. For most common usage scenarios, standard user privileges are sufficient to run df effectively.

Essential Df Command Options

The df command offers several options to customize its output and provide information in formats that are easier to interpret or more suitable for specific tasks. Understanding these options can significantly enhance your ability to monitor disk space effectively.

Human-Readable Output Formats

One of the most frequently used options is -h (or --human-readable), which displays sizes in a more readable format using suffixes like K, M, G, and T for kilobyte, megabyte, gigabyte, and terabyte, respectively.

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           796M  1.9M  794M   1% /run
/dev/sda1        94G   66G   23G  75% /
tmpfs           3.9G   13M  3.9G   1% /dev/shm

For those who prefer powers of 1000 instead of 1024, the -H option provides sizes using the SI prefixes (where 1KB = 1000 bytes, 1MB = 1000KB, etc.).

$ df -H
Filesystem      Size  Used Avail Use% Mounted on
udev            4.1G     0  4.1G   0% /dev
tmpfs           830M  1.9M  825M   1% /run
/dev/sda1        99G   69G   25G  75% /
tmpfs           4.2G   13M  4.1G   1% /dev/shm

Unit-Specific Display Options

If you prefer to see information in specific units, df provides several options:

  • -k: Display sizes in 1-kilobyte blocks (default)
  • -m: Display sizes in 1-megabyte blocks
  • --block-size=SIZE: Display sizes in blocks of the specified SIZE
$ df -m
Filesystem     1M-blocks    Used Available Use% Mounted on
udev               3951       0      3951   0% /dev
tmpfs               796       2       793   1% /run
/dev/sda1         95318   67085    23305  75% /
tmpfs              3976      13      3964   1% /dev/shm

Displaying Filesystem Types

To include the filesystem type in the output, use the -T option:

$ df -T
Filesystem     Type     1K-blocks     Used Available Use% Mounted on
udev           devtmpfs   4046836        0   4046836   0% /dev
tmpfs          tmpfs       814200     1852    812348   1% /run
/dev/sda1      ext4      97605056 68694600  23864072  75% /
tmpfs          tmpfs      4071004    12944   4058060   1% /dev/shm

This information can be particularly useful when troubleshooting issues specific to certain filesystem types or when you need to verify the filesystem type of a mounted device.

Total Disk Usage

To display the total disk usage across all listed filesystems, use the --total option:

$ df -h --total
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           796M  1.9M  794M   1% /run
/dev/sda1        94G   66G   23G  75% /
tmpfs           3.9G   13M  3.9G   1% /dev/shm
total           103G   66G   31G  68% -

This overview helps you understand your overall disk usage at a glance, which is particularly helpful in environments with numerous filesystems.

Practical Examples for Everyday Use

Let’s explore some common scenarios where the df command proves invaluable for system administration and maintenance tasks.

Checking Overall System Disk Space Usage

The most basic and common usage is checking overall disk space with the human-readable option:

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           796M  1.9M  794M   1% /run
/dev/sda1        94G   66G   23G  75% /
tmpfs           3.9G   13M  3.9G   1% /dev/shm
/dev/sdb1       932G  820G   65G  93% /data

This quick overview helps identify which filesystems are approaching their capacity limits. In this example, the /data partition is at 93% utilization, which might warrant attention.

Monitoring Specific Filesystem or Partition

To check a specific filesystem or directory, simply provide its path as an argument:

$ df -h /data
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb1       932G  820G   65G  93% /data

This focused approach is useful when you’re only concerned about a particular partition or mount point, such as a database directory or user home directories.

Filtering Output by Filesystem Type

You can filter the output to show only specific filesystem types using the -t option:

$ df -h -t ext4
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        94G   66G   23G  75% /
/dev/sdb1       932G  820G   65G  93% /data

This example shows only ext4 filesystems, which is helpful when you want to ignore temporary, virtual, or network filesystems.

Examining Space on Remote Filesystems

The df command can also report on network filesystems like NFS:

$ df -h /mnt/nfs_share
Filesystem           Size  Used Avail Use% Mounted on
server:/shared_data  2.0T  1.2T  800G  60% /mnt/nfs_share

This capability allows you to monitor remote storage just as easily as local disks, which is essential in environments with distributed storage resources.

Real-World Application

In a production environment, you might use df to quickly diagnose an application failure. For instance, if a database stops accepting new data, a simple df check might reveal that its filesystem is at 100% capacity:

$ df -h /var/lib/mysql
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdc1       500G  500G     0 100% /var/lib/mysql

This immediate insight allows you to take appropriate action, such as cleaning up old logs or adding more storage capacity, before the issue affects more critical systems.

Customizing Df Output

The df command offers powerful customization options that allow you to tailor the output to your specific needs, making it more focused and readable.

Using –output to Select Specific Columns

With the --output option, you can select exactly which columns to display:

$ df --output=source,size,used,avail,pcent,target -h
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           796M  1.9M  794M   1% /run
/dev/sda1        94G   66G   23G  75% /
tmpfs           3.9G   13M  3.9G   1% /dev/shm

The available fields for the --output option include:

  • source: The filesystem source (device, UUID, label)
  • fstype: Filesystem type
  • size: Total size of the filesystem
  • used: Space used on the filesystem
  • avail: Available space on the filesystem
  • pcent: Usage percentage
  • target: Mount point
  • itotal: Total inodes
  • iused: Used inodes
  • iavail: Available inodes
  • ipercent: Inode usage percentage
  • file: For creating a customized filename output
  • inode: For creating a customized inode output

Creating Simplified Outputs

For environments where you need a cleaner, more focused report, you can create simplified outputs. For example, to display only filesystem, size, used percentage, and mount point:

$ df --output=source,size,pcent,target -h
Filesystem      Size Use% Mounted on
udev            3.9G   0% /dev
tmpfs           796M   1% /run
/dev/sda1        94G  75% /
tmpfs           3.9G   1% /dev/shm

This type of streamlined output can be particularly useful in scripts or when generating reports where unnecessary information would just add clutter.

Best Practices for Report Generation

When generating reports for system status or monitoring purposes, consider these best practices:

  1. Use human-readable formats (-h) for reports that will be read by humans
  2. Include filesystem types (-T) when troubleshooting filesystem-specific issues
  3. Filter out irrelevant filesystems to focus on important data
  4. Include the --total option for summary information
  5. For automated processing, use the default block output without human-readable formatting
  6. Format output with --output to match the specific information needs of your audience
# Example of a comprehensive yet focused report
$ df -hT --output=source,fstype,size,used,avail,pcent,target | grep -v "tmpfs\|devtmpfs"
Filesystem     Type    Size  Used Avail Use% Mounted on
/dev/sda1      ext4     94G   66G   23G  75% /
/dev/sdb1      ext4    932G  820G   65G  93% /data
server:/share  nfs     2.0T  1.2T  800G  60% /mnt/nfs_share

This custom report provides a clear overview of only the significant storage devices while including the filesystem type for better context.

Advanced Usage Scenarios

Beyond the basic functionalities, the df command offers advanced options that provide deeper insights into filesystem usage and help diagnose complex issues.

Checking Inode Usage with -i Option

Filesystems allocate inodes to store metadata about files. Even with plenty of disk space available, a filesystem can become unusable if it runs out of inodes. The -i option shows inode usage instead of block usage:

$ df -i
Filesystem       Inodes   IUsed    IFree IUse% Mounted on
udev            1011709     546  1011163    1% /dev
tmpfs           1017751     954  1016797    1% /run
/dev/sda1       6291456 1255409  5036047   20% /
tmpfs           1017751       4  1017747    1% /dev/shm

This information is crucial when dealing with filesystems containing many small files, as each file consumes at least one inode regardless of its size. High inode usage can occur even when disk space usage appears normal, especially in directories with thousands of small files like mail servers or source code repositories.

Examining All Filesystems with -a

By default, df omits certain filesystem types. The -a option includes all filesystems, including virtual ones like procfs and sysfs:

$ df -a
Filesystem     1K-blocks     Used Available Use% Mounted on
sysfs                  0        0         0    - /sys
proc                   0        0         0    - /proc
udev             4046836        0   4046836   0% /dev
devpts                 0        0         0    - /dev/pts
tmpfs             814200     1852    812348   1% /run
/dev/sda1       97605056 68694600  23864072  75% /
securityfs             0        0         0    - /sys/kernel/security
...

This comprehensive view can be useful for debugging or when you need to see every mounted filesystem without exceptions.

Excluding Specific Filesystem Types with -x

The -x option allows you to exclude specific filesystem types, which is helpful for focusing on physical storage devices:

$ df -h -x tmpfs -x devtmpfs
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        94G   66G   23G  75% /
/dev/sdb1       932G  820G   65G  93% /data

This example excludes tmpfs and devtmpfs filesystems, providing a cleaner output that focuses on physical disks.

Limiting Output to Local Filesystems with -l

When working in environments with network filesystems, the -l option limits the display to local filesystems:

$ df -h -l
Filesystem      Size  Used Avail Use% Mounted on
udev            3.9G     0  3.9G   0% /dev
tmpfs           796M  1.9M  794M   1% /run
/dev/sda1        94G   66G   23G  75% /
tmpfs           3.9G   13M  3.9G   1% /dev/shm
/dev/sdb1       932G  820G   65G  93% /data

This option excludes NFS, SMB, and other network filesystems, which is particularly useful in environments with many remotely mounted directories.

Combining Multiple Options for Detailed Analysis

For a comprehensive analysis, you can combine multiple options to create a highly targeted output:

$ df -hTil --output=source,fstype,itotal,iused,iavail,ipcent,size,used,avail,pcent,target | grep -v "tmpfs\|devtmpfs"
Filesystem     Type    Inodes   IUsed    IFree IUse%   Size  Used Avail Use% Mounted on
/dev/sda1      ext4   6291456 1255409  5036047   20%    94G   66G   23G  75% /
/dev/sdb1      ext4  61054976  983254 60071722    2%   932G  820G   65G  93% /data

This complex example provides a detailed view of both space and inode usage for physical disks, excluding virtual filesystems. Such comprehensive information helps in thorough system analysis and capacity planning.

Troubleshooting Disk Space Issues

Effective troubleshooting of disk space issues often begins with the df command. Here are some common scenarios and how to diagnose them using df.

Identifying Filesystems Approaching Capacity

Regular monitoring with df helps identify filesystems that are reaching critical capacity levels:

$ df -h | awk '{ if ($5 > "85%") print $0 }'
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb1       932G  820G   65G  93% /data

This command filters output to show only filesystems with more than 85% usage, allowing you to prioritize cleanup efforts on the most critical areas.

Diagnosing Inode Exhaustion

Sometimes a filesystem appears to have plenty of space but still reports “no space left on device” errors. This often indicates inode exhaustion:

$ df -i | awk '{ if ($5 > "90%") print $0 }'
Filesystem       Inodes   IUsed    IFree IUse% Mounted on
/dev/sdc1       1048576 1046523     2053   99% /var/mail

In this example, the mail partition has nearly exhausted its inodes despite potentially having adequate disk space. The solution might involve increasing the number of inodes when reformatting the filesystem or migrating to a filesystem with dynamic inode allocation.

Understanding Discrepancies Between df and du

Users often notice that df and du report different usage values for the same filesystem. This discrepancy typically occurs due to:

  1. Files that are open but have been deleted (still consuming space according to df)
  2. Hidden space reserved for the superuser (typically 5% on ext filesystems)
  3. Differences in block counting methods between the two utilities

To investigate such discrepancies:

$ df -h /var
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        94G   66G   23G  75% /

$ du -sh /var
58G     /var

This situation might indicate deleted files that are still open by running processes. You can find these with:

$ lsof | grep deleted

Analyzing “Filesystem Not Mounted” Messages

If df reports that a filesystem is not mounted when you believe it should be, verify the mount points:

$ mount | grep sdc
/dev/sdc1 on /mnt/backup type ext4 (rw,relatime)

$ df -h | grep sdc

If the mount is shown in the mount command output but not in df, it might indicate filesystem corruption requiring fsck or other repair tools.

Integrating Df with Other Commands

The true power of the df command emerges when combined with other Linux utilities to create more sophisticated disk space monitoring solutions.

Piping df Output to grep for Filtering

To focus on specific filesystems or patterns, pipe df output through grep:

$ df -h | grep "^/dev/sd"
/dev/sda1        94G   66G   23G  75% /
/dev/sdb1       932G  820G   65G  93% /data
/dev/sdc1       500G  180G  295G  38% /backup

This command filters the output to show only devices that match the pattern “/dev/sd”, effectively displaying only physical disk partitions.

Using awk for Conditional Reporting

For more complex conditional filtering, awk provides powerful capabilities:

$ df -h | awk '$5 > "70%" && $1 ~ /^\/dev/ {print $0}'
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        94G   66G   23G  75% /
/dev/sdb1       932G  820G   65G  93% /data

This example shows physical disk partitions with usage exceeding 70%, helping you focus on filesystems that need attention.

Combining with sort for Organizing Output

To identify the most heavily used filesystems, combine df with sort:

$ df -h | grep "^/dev" | sort -k5 -nr
/dev/sdb1       932G  820G   65G  93% /data
/dev/sda1        94G   66G   23G  75% /
/dev/sdc1       500G  180G  295G  38% /backup

This command sorts the output by usage percentage in descending order, showing the most utilized filesystems first.

Using watch for Continuous Monitoring

The watch command allows you to run df at regular intervals to observe changes in disk usage:

$ watch -n 60 "df -h | grep '^/dev'"

This command refreshes the output every 60 seconds, providing a simple real-time monitoring solution for critical filesystems.

Automating Disk Space Monitoring

Automated monitoring helps ensure that disk space issues are identified and addressed before they cause system failures. The df command is the foundation for many such automation solutions.

Creating Cron Jobs for Regular Monitoring

Set up a cron job to check disk space regularly and alert when thresholds are exceeded:

# Add to crontab with 'crontab -e'
0 * * * * /path/to/disk_monitor.sh

Where disk_monitor.sh might contain:

#!/bin/bash
# Simple disk space monitoring script

THRESHOLD=90
FILESYSTEMS=$(df -h | grep "^/dev" | awk '{print $1 ":" $5 ":" $6}')

for FS in $FILESYSTEMS; do
    DEVICE=$(echo $FS | cut -d: -f1)
    USAGE=$(echo $FS | cut -d: -f2 | cut -d% -f1)
    MOUNT=$(echo $FS | cut -d: -f3)
    
    if [ $USAGE -gt $THRESHOLD ]; then
        echo "ALERT: Filesystem $DEVICE mounted on $MOUNT is at $USAGE% capacity!"
        # Add email or notification commands here
    fi
done

Sending Email Alerts for Low Disk Space

Extend the monitoring script to send email alerts when space is running low:

if [ $USAGE -gt $THRESHOLD ]; then
    MESSAGE="ALERT: Filesystem $DEVICE mounted on $MOUNT is at $USAGE% capacity!"
    echo $MESSAGE | mail -s "Disk Space Alert on $(hostname)" admin@example.com
fi

This simple addition ensures that administrators receive timely notifications of potential disk space issues.

Threshold-Based Monitoring Strategies

Different filesystems might require different threshold levels. For example:

  • Root filesystem: Alert at 85% to prevent system instability
  • Database volumes: Alert at 75% to ensure proper database performance
  • Log directories: Alert at 90% but implement log rotation to prevent issues
  • Backup destinations: Alert at 95% as they’re designed to fill up to capacity

Customize your monitoring thresholds based on the criticality and purpose of each filesystem.

Best Practices for Disk Management

Effective disk management goes beyond monitoring. Here are some best practices that incorporate the df command:

Regular Monitoring Schedules

Establish a consistent monitoring schedule that includes:

  • Hourly checks for critical production systems
  • Daily reports for trending analysis
  • Weekly comprehensive reviews of all filesystems
  • Monthly capacity planning based on growth trends

Regular df checks should be part of standard operational procedures for system administrators.

Setting Appropriate Thresholds

Different environments require different alert thresholds. As a general guideline:

  • Development environments: 90-95% usage before alerting
  • Production systems: 75-85% usage before alerting
  • Database servers: 70-80% usage before alerting
  • Mail servers: Monitor both space and inode usage, alerting at 80% for either

Use historical data to refine these thresholds based on growth patterns specific to your environment.

Proactive Disk Space Management

Don’t wait for alerts to manage disk space. Implement proactive measures:

  • Regular cleanup of temporary files and old logs
  • Automated archiving of older data
  • Periodic review of large directories using tools like du
  • Implementation of disk quotas where appropriate

Combining these practices with regular df monitoring creates a robust disk management strategy.

Comparison with Related Linux Commands

The df command is part of a family of disk management utilities, each with specific strengths and use cases.

df vs. du Command

While df provides filesystem-level information, du (disk usage) reports file and directory sizes:

# df shows filesystem information
$ df -h /home
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        94G   66G   23G  75% /

# du shows directory sizes
$ du -sh /home/*
4.2G    /home/user1
1.8G    /home/user2

Use df for overall filesystem status and du for identifying which directories consume the most space.

df vs. fdisk

The fdisk command manages partition tables, while df reports on mounted filesystems:

# df shows mounted filesystems
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        94G   66G   23G  75% /

# fdisk shows partition information
$ sudo fdisk -l /dev/sda
Disk /dev/sda: 100 GiB
Device     Boot Start       End   Sectors  Size Id Type
/dev/sda1  *     2048 209713151 209711104  100G 83 Linux

Use fdisk for partition management and df for monitoring space on those partitions.

df vs. lsblk

The lsblk command shows block device information in a tree structure, while df focuses on filesystem usage:

# df shows filesystem usage
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        94G   66G   23G  75% /

# lsblk shows device hierarchy
$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0   100G  0 disk 
└─sda1   8:1    0   100G  0 part /

Use lsblk to understand device relationships and df to check space utilization.

Common Issues and Solutions

Despite its simplicity, df can sometimes present confusing results. Here are solutions to common issues:

Why df Might Show Incorrect Disk Usage

If df shows higher usage than expected, consider these possible causes:

  1. Open but deleted files: Processes keeping files open after deletion
# Find and restart processes holding deleted files
$ lsof | grep deleted
  1. Reserved blocks: Default 5% reservation for root on ext filesystems
# Adjust reserved space percentage
$ sudo tune2fs -m 2 /dev/sda1
  1. Hidden directories: Overlooked spaces like snapshots or trash
# Look for hidden space consumers
$ sudo du -shx /* | sort -hr

Handling “No Space Left” Errors When Space Exists

If you encounter “no space left on device” errors despite df showing available space:

  1. Check inode usage
$ df -i
  1. Verify file descriptor limits
$ ulimit -n
  1. Look for filesystem corruption
$ sudo fsck -f /dev/sda1

Network Filesystem Reporting Issues

Network filesystems like NFS might show inconsistent results with df due to:

  1. Caching effects: Client-side caching affecting reported sizes
  2. Network delays: Temporary discrepancies during synchronization
  3. Permission issues: Incomplete reporting due to access restrictions

Regular cache clearing and ensuring proper permissions can help minimize these inconsistencies.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button