Posted on
Administration

Monitoring Disk Usage with Bash Commands

Author
  • User
    Linux Bash
    Posts by this author
    Posts by this author

Monitoring disk usage is essential for maintaining system health and ensuring adequate storage space. Here’s how you can monitor disk usage using various Bash commands:


1. Check Disk Space Usage

  • Command: df
  • Usage:

    • View disk usage for all mounted filesystems:
    df -h
    
    • -h: Displays output in human-readable format (e.g., GB, MB).

    • Filter for a specific filesystem or directory:

    df -h /path/to/directory
    

2. Analyze Directory Sizes

  • Command: du
  • Usage:
    • Display the size of a directory and its subdirectories: bash du -h /path/to/directory
    • Show only the total size of a directory: bash du -sh /path/to/directory
    • -s: Summarize the total size.
    • -h: Human-readable format.

3. Monitor Disk Space in Real-Time

  • Command: watch
  • Usage:
    • Use watch to run df repeatedly at intervals: bash watch -n 5 df -h
    • -n 5: Refresh every 5 seconds.

4. Find Large Files

  • Command: find
  • Usage:
    • Search for files larger than 1 GB: bash find /path/to/search -type f -size +1G
    • List large files in human-readable format: bash find /path/to/search -type f -size +1G -exec ls -lh {} \;

5. Monitor Inode Usage

  • Command: df (with the -i option)
  • Usage:
    • Check inode usage to ensure you’re not running out: bash df -i

6. Automate Monitoring with a Script

  • Example Bash Script:

    #!/bin/bash
    
    # Define thresholds
    THRESHOLD=80
    ALERT_EMAIL="admin@example.com"
    
    # Monitor disk space
    df -h | awk 'NR>1 {if ($5+0 > '"$THRESHOLD"') print $0}' > /tmp/disk_alert.txt
    
    # Send email alert if thresholds are exceeded
    if [ -s /tmp/disk_alert.txt ]; then
    mail -s "Disk Space Alert" "$ALERT_EMAIL" < /tmp/disk_alert.txt
    fi
    

7. System-Wide Disk Monitoring Tools

Consider using tools like ncdu or iotop for more advanced monitoring: - ncdu: A fast, interactive disk usage analyzer. bash sudo apt install ncdu # For Debian-based systems ncdu /path/to/analyze - iotop: Monitor real-time disk I/O usage.


These commands and tools provide both basic and advanced methods for monitoring disk usage, helping you maintain system performance and prevent storage issues.