Practical Methods for Checking Disk Space of Current Partition in Bash

Nov 23, 2025 · Programming · 7 views · 7.8

Keywords: Bash scripting | disk space checking | df command | stat command | installation scripts

Abstract: This article provides an in-depth exploration of various methods for checking disk space of the current partition in Bash scripts, with focus on the df command's -pwd parameter and the flexible application of the stat command. By comparing output formats and parsing approaches of different commands, it offers complete solutions suitable for installation scripts and system monitoring, including handling output format issues caused by long pathnames and obtaining precise byte-level space information.

Importance of Disk Space Checking

When writing Bash installation scripts, disk space checking is a crucial pre-validation step. Users typically run installation scripts directly in the target directory, making it essential to accurately obtain available space information for the partition where that directory resides. While the traditional df command can display space usage for all filesystems, script environments require more precise targeting capabilities.

Using df Command for Specific Directory Checking

The df -k . command provides the most straightforward solution, where the -k parameter specifies displaying space information in KB units, and . represents the current working directory. This command returns detailed space usage statistics for the partition containing the current directory, including total space, used space, and available space.

For scenarios requiring checking of specific directories, the format df -k /some/dir can be used. This approach's advantage lies in precisely targeting the partition containing the destination directory, avoiding interference from space information of other partitions.

Handling Output Format Issues

In practical usage, the output format of the df command may vary depending on terminal width. When mount point paths are long, output may wrap to multiple lines, increasing script parsing complexity. An effective solution is using df $PWD | awk '/[0-9]%/{print $(NF-2)}', where this combined command filters lines containing percentage numbers using awk and extracts the second-to-last field (available space).

The key here is understanding the field structure of df output: the last field $(NF) is the mount point, the second-to-last field $(NF-1) is the used space percentage, and the third-to-last field $(NF-2) contains the available block count. Through this precise field positioning, correct extraction of required information can be ensured across various output formats.

Using stat Command for Precise Space Information

For scenarios requiring finer control, the stat command offers a better solution. stat -f --format="%a*%S" . outputs the available block count multiplied by block size for the current directory's filesystem, providing precise available byte count.

In Bash scripts, available space can be calculated as follows:

available_bytes=$(($(stat -f --format="%a*%S" .)))

This method offers several advantages:

Command Comparison and Selection Guidelines

df -k . is suitable for quickly obtaining human-readable space information, particularly in scenarios requiring immediate determination of whether installation requirements are met. Its output includes total space, used space, available space, and usage percentage, providing a complete space usage overview.

The stat command is better suited for scenarios requiring precise numerical calculations, such as when scripts need to compare against specific thresholds or calculate how many files can fit in remaining space. By directly outputting byte counts, it avoids precision loss that might occur during unit conversions.

Practical Application Example

Below is a complete installation script space checking function example:

check_disk_space() {
    local required_mb=$1
    local available_kb
    
    # Use df to get available space (KB)
    available_kb=$(df -k . | awk 'NR==2 {print $4}')
    
    # Convert to MB and compare
    if [ $((available_kb / 1024)) -lt $required_mb ]; then
        echo "Error: Insufficient disk space. Required ${required_mb}MB, available $((available_kb / 1024))MB"
        exit 1
    else
        echo "Disk space check passed: $((available_kb / 1024))MB available"
    fi
}

This function demonstrates how to apply theoretical methods to actual scripts, incorporating error handling and user-friendly messaging.

Supplementary Tool Introduction

Beyond the primary methods discussed, the du command plays an important role in disk space management. du -sh displays total space usage of the current directory, with the -s parameter providing summarization and -h parameter offering human-readable format. This is particularly useful when analyzing space occupancy of specific directories or files, serving as a valuable complement to the df command.

Best Practices Summary

When selecting disk space checking methods, consider the following factors: script execution environment, required precision level, and output format stability requirements. For most installation script scenarios, df -k . combined with appropriate parsing logic is sufficient; for scenarios requiring high-precision calculations, the stat command is the better choice. Regardless of the method chosen, appropriate error handling mechanisms should be incorporated to ensure scripts exit gracefully or provide clear error messages when command execution fails.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.