How to show memory usage → free

How to Show Memory Usage → free Memory management is a critical aspect of system administration and performance monitoring in Linux environments. Understanding how to effectively monitor memory usage helps administrators optimize system performance, troubleshoot issues, and ensure applications have adequate resources. The `free` command is one of the most fundamental and widely-used tools for displaying memory usage information in Linux systems. This comprehensive guide will teach you everything you need to know about using the `free` command to monitor memory usage, from basic syntax to advanced techniques and troubleshooting scenarios. Table of Contents 1. [Prerequisites](#prerequisites) 2. [Understanding Memory Types](#understanding-memory-types) 3. [Basic free Command Usage](#basic-free-command-usage) 4. [Command Options and Flags](#command-options-and-flags) 5. [Practical Examples](#practical-examples) 6. [Advanced Usage Scenarios](#advanced-usage-scenarios) 7. [Interpreting Output](#interpreting-output) 8. [Troubleshooting Common Issues](#troubleshooting-common-issues) 9. [Best Practices](#best-practices) 10. [Alternative Memory Monitoring Tools](#alternative-memory-monitoring-tools) 11. [Conclusion](#conclusion) Prerequisites Before diving into the `free` command, ensure you have: - Basic knowledge of Linux command-line interface - Access to a Linux system (any distribution) - Terminal or SSH access to the system - Basic understanding of memory concepts (RAM, swap, cache) - Root or sudo privileges for certain advanced operations System Requirements: - Any modern Linux distribution - The `free` command is part of the procps package (usually pre-installed) - No additional software installation required Understanding Memory Types Before exploring the `free` command, it's essential to understand the different types of memory that Linux systems manage: Physical Memory (RAM) Physical memory refers to the actual RAM modules installed in your system. This is the primary workspace for running applications and the operating system. Virtual Memory Virtual memory combines physical RAM with swap space to provide applications with a larger memory address space than physically available. Swap Memory Swap space is disk storage used as an extension of RAM when physical memory becomes full. It's slower than RAM but prevents out-of-memory conditions. Buffer and Cache Memory - Buffers: Temporary storage for data being written to or read from disk - Cache: Stores frequently accessed data from disk for faster retrieval Basic free Command Usage The `free` command displays information about system memory usage by reading data from `/proc/meminfo`. Here's the basic syntax: ```bash free [options] ``` Simple Usage Example ```bash $ free total used free shared buff/cache available Mem: 8165416 2847392 3421856 156432 1896168 4967676 Swap: 2097148 0 2097148 ``` This output shows memory usage in kilobytes by default, displaying both physical memory (Mem) and swap space information. Command Options and Flags The `free` command offers various options to customize output format and information display: Display Units Human-Readable Format (-h) ```bash $ free -h total used free shared buff/cache available Mem: 7.8Gi 2.7Gi 3.3Gi 153Mi 1.8Gi 4.7Gi Swap: 2.0Gi 0B 2.0Gi ``` Bytes (-b) ```bash $ free -b total used free shared buff/cache available Mem: 8361385984 2915356672 3503616000 160161792 1942413312 5086171136 Swap: 2147479552 0 2147479552 ``` Kilobytes (-k) - Default ```bash $ free -k total used free shared buff/cache available Mem: 8165416 2847392 3421856 156432 1896168 4967676 Swap: 2097148 0 2097148 ``` Megabytes (-m) ```bash $ free -m total used free shared buff/cache available Mem: 7973 2780 3341 152 1851 4851 Swap: 2047 0 2047 ``` Gigabytes (-g) ```bash $ free -g total used free shared buff/cache available Mem: 7 2 3 0 1 4 Swap: 1 0 1 ``` Continuous Monitoring Update Interval (-s) Monitor memory usage continuously with specified update intervals: ```bash $ free -s 5 Updates every 5 seconds ``` Count Updates (-c) Limit the number of updates: ```bash $ free -s 2 -c 10 Updates every 2 seconds for 10 iterations ``` Output Formatting Wide Output (-w) Provides wider output format for better readability: ```bash $ free -w total used free shared buffers cache available Mem: 8165416 2847392 3421856 156432 234568 1661600 4967676 Swap: 2097148 0 2097148 ``` Total Summary (-t) Shows total of physical memory and swap: ```bash $ free -t total used free shared buff/cache available Mem: 8165416 2847392 3421856 156432 1896168 4967676 Swap: 2097148 0 2097148 Total: 10262564 2847392 5518004 ``` Practical Examples Example 1: Basic System Health Check For a quick system memory overview: ```bash $ free -h total used free shared buff/cache available Mem: 7.8Gi 2.7Gi 3.3Gi 153Mi 1.8Gi 4.7Gi Swap: 2.0Gi 0B 2.0Gi ``` Analysis: This system has 7.8GB total RAM, with 2.7GB actively used by applications, 3.3GB completely free, and 1.8GB used for buffers/cache. The available memory (4.7GB) indicates how much memory is available for new applications. Example 2: Monitoring During High Load Monitor memory usage during system stress: ```bash $ free -h -s 1 Monitor every second during heavy operations ``` Example 3: Detailed Memory Analysis For comprehensive memory information: ```bash $ free -w -h -t total used free shared buffers cache available Mem: 7.8Gi 2.7Gi 3.3Gi 153Mi 229Mi 1.6Gi 4.7Gi Swap: 2.0Gi 0B 2.0Gi Total: 9.8Gi 2.7Gi 5.3Gi ``` Example 4: Scripting and Automation Extract specific memory values for scripts: ```bash #!/bin/bash Get available memory in MB AVAILABLE_MB=$(free -m | awk 'NR==2{print $7}') echo "Available memory: ${AVAILABLE_MB}MB" Check if available memory is below threshold THRESHOLD=1000 if [ $AVAILABLE_MB -lt $THRESHOLD ]; then echo "Warning: Low memory available!" # Send alert or take action fi ``` Example 5: Memory Usage Percentage Calculate memory usage percentage: ```bash #!/bin/bash Calculate memory usage percentage MEMORY_INFO=$(free | grep '^Mem:') TOTAL=$(echo $MEMORY_INFO | awk '{print $2}') USED=$(echo $MEMORY_INFO | awk '{print $3}') PERCENTAGE=$(awk "BEGIN {printf \"%.2f\", $USED/$TOTAL*100}") echo "Memory usage: ${PERCENTAGE}%" ``` Advanced Usage Scenarios Combining with Other Commands Memory Usage with Process Information ```bash $ free -h && echo "Top memory consumers:" && ps aux --sort=-%mem | head -5 ``` System Overview Script ```bash #!/bin/bash echo "=== System Memory Report ===" echo "Date: $(date)" echo "" echo "Memory Usage:" free -h echo "" echo "Swap Usage Details:" swapon --show echo "" echo "Memory-intensive processes:" ps aux --sort=-%mem | head -10 ``` Monitoring Memory Trends Logging Memory Usage ```bash #!/bin/bash Log memory usage to file LOG_FILE="/var/log/memory_usage.log" while true; do echo "$(date): $(free -h | grep '^Mem:')" >> $LOG_FILE sleep 300 # Log every 5 minutes done ``` Memory Alert System ```bash #!/bin/bash Memory monitoring with alerts THRESHOLD=90 # Alert when memory usage exceeds 90% check_memory() { USED_PERCENT=$(free | grep '^Mem:' | awk '{printf "%.0f", $3/$2 * 100}') if [ $USED_PERCENT -gt $THRESHOLD ]; then echo "ALERT: Memory usage at ${USED_PERCENT}%" | mail -s "High Memory Usage" admin@example.com fi } while true; do check_memory sleep 60 done ``` Interpreting Output Understanding the `free` command output is crucial for effective memory management: Column Meanings | Column | Description | |--------|-------------| | total | Total installed physical RAM | | used | Memory currently used by running processes | | free | Completely unused memory | | shared | Memory used by tmpfs filesystems | | buff/cache | Memory used for buffers and cache | | available | Estimation of memory available for starting new applications | Key Concepts Available vs. Free Memory - Free: Completely unused memory - Available: Memory that can be made available to applications (includes reclaimable cache) Buffer/Cache Memory This memory is used by the kernel for disk caching but can be freed when applications need it. It's not "wasted" memory but rather an optimization. Swap Usage Interpretation - 0 swap used: Good indicator of sufficient RAM - Heavy swap usage: May indicate insufficient physical memory - Occasional swap: Normal for inactive processes Memory Health Indicators Healthy System Signs ```bash $ free -h total used free shared buff/cache available Mem: 8.0Gi 2.1Gi 4.2Gi 64Mi 1.7Gi 5.6Gi Swap: 2.0Gi 0B 2.0Gi ``` - Low swap usage - Reasonable available memory - Good buffer/cache utilization Warning Signs ```bash $ free -h total used free shared buff/cache available Mem: 8.0Gi 7.8Gi 100Mi 64Mi 100Mi 150Mi Swap: 2.0Gi 1.5Gi 500Mi ``` - High memory usage (>90%) - Low available memory - Significant swap usage Troubleshooting Common Issues Issue 1: High Memory Usage Symptoms: System slowness, high memory usage reported by `free` Diagnosis: ```bash $ free -h $ ps aux --sort=-%mem | head -10 $ top -o %MEM ``` Solutions: 1. Identify memory-intensive processes 2. Restart or optimize problematic applications 3. Consider adding more RAM 4. Implement memory limits using cgroups Issue 2: Swap Thrashing Symptoms: Heavy swap usage, system unresponsiveness Diagnosis: ```bash $ free -h $ vmstat 1 5 $ iotop -o # Monitor swap I/O ``` Solutions: 1. Increase physical RAM 2. Optimize applications to use less memory 3. Adjust swappiness parameter: ```bash $ echo 10 > /proc/sys/vm/swappiness ``` Issue 3: Memory Leaks Symptoms: Gradually increasing memory usage Diagnosis: ```bash Monitor memory usage over time $ watch -n 5 'free -h' Track specific process memory growth $ ps -p -o pid,ppid,cmd,%mem,%cpu --sort=-%mem ``` Solutions: 1. Restart affected applications 2. Update software to fix known memory leaks 3. Implement application monitoring 4. Use memory debugging tools (valgrind, etc.) Issue 4: Incorrect Memory Reporting Symptoms: Unexpected memory values Verification: ```bash $ free -h $ cat /proc/meminfo $ dmidecode --type memory # Hardware memory info ``` Solutions: 1. Check hardware memory installation 2. Verify kernel memory detection 3. Check for memory reserved by hardware/kernel Best Practices Regular Monitoring 1. Establish Baselines: ```bash # Create daily memory reports $ free -h > /var/log/memory-$(date +%Y%m%d).log ``` 2. Automated Monitoring: Set up cron jobs for regular memory checks: ```bash # Add to crontab /15 * /usr/bin/free -h >> /var/log/memory.log ``` Memory Optimization 1. Configure Appropriate Swap: - Systems with <2GB RAM: 2x RAM size - Systems with 2-8GB RAM: Equal to RAM size - Systems with >8GB RAM: 0.5x RAM size or 8GB minimum 2. Optimize Application Memory: ```bash # Use memory-efficient alternatives # Monitor application memory patterns # Implement proper garbage collection ``` 3. System Tuning: ```bash # Adjust kernel parameters echo 'vm.swappiness = 10' >> /etc/sysctl.conf echo 'vm.vfs_cache_pressure = 50' >> /etc/sysctl.conf ``` Documentation and Alerting 1. Document Memory Patterns: - Record normal memory usage patterns - Document peak usage times - Maintain capacity planning records 2. Implement Alerting: ```bash # Example Nagios check #!/bin/bash MEMORY_USAGE=$(free | grep '^Mem:' | awk '{printf "%.0f", $3/$2 * 100}') if [ $MEMORY_USAGE -gt 90 ]; then echo "CRITICAL - Memory usage: ${MEMORY_USAGE}%" exit 2 elif [ $MEMORY_USAGE -gt 80 ]; then echo "WARNING - Memory usage: ${MEMORY_USAGE}%" exit 1 else echo "OK - Memory usage: ${MEMORY_USAGE}%" exit 0 fi ``` Security Considerations 1. Monitor for Suspicious Activity: Sudden memory usage spikes could indicate malicious activity 2. Implement Resource Limits: ```bash # Use ulimit for user processes ulimit -m 1000000 # Limit memory to ~1GB # Use systemd service limits [Service] MemoryLimit=1G ``` Alternative Memory Monitoring Tools While `free` is excellent for basic memory monitoring, consider these alternatives for specific use cases: /proc/meminfo Direct access to kernel memory statistics: ```bash $ cat /proc/meminfo | head -20 ``` vmstat Virtual memory statistics: ```bash $ vmstat -s # Memory statistics $ vmstat 1 5 # Real-time monitoring ``` htop/top Interactive process and memory monitoring: ```bash $ htop $ top -o %MEM ``` smem Advanced memory reporting tool: ```bash $ smem -t -k # Memory usage by process $ smem -m # System-wide memory map ``` sar (System Activity Reporter) Historical memory usage data: ```bash $ sar -r 1 5 # Memory utilization $ sar -W 1 5 # Swap statistics ``` Conclusion The `free` command is an indispensable tool for Linux system administrators and users who need to monitor memory usage effectively. Throughout this comprehensive guide, we've explored everything from basic usage to advanced monitoring scenarios, troubleshooting techniques, and best practices. Key Takeaways 1. Understanding Memory Types: Distinguishing between different memory categories (used, free, available, buff/cache) is crucial for accurate system assessment. 2. Command Flexibility: The `free` command offers numerous options for customizing output format, monitoring intervals, and display units to suit different needs. 3. Interpretation Skills: Properly interpreting `free` command output helps identify system health, potential issues, and optimization opportunities. 4. Proactive Monitoring: Regular memory monitoring using automated scripts and alerts prevents system performance issues and downtime. 5. Holistic Approach: Combining `free` with other system monitoring tools provides comprehensive insights into system performance. Next Steps To further enhance your memory monitoring capabilities: 1. Implement Automated Monitoring: Set up regular memory monitoring scripts and alerts based on the examples provided in this guide. 2. Explore Advanced Tools: Investigate specialized memory analysis tools like `smem`, `valgrind`, or `perf` for deeper insights. 3. Develop Monitoring Strategy: Create a comprehensive system monitoring strategy that includes memory, CPU, disk, and network monitoring. 4. Practice Troubleshooting: Use the troubleshooting scenarios in this guide to practice identifying and resolving memory-related issues. 5. Stay Updated: Keep up with new developments in Linux memory management and monitoring tools. Memory management is a critical aspect of system administration, and mastering the `free` command is just the beginning. With the knowledge gained from this guide, you're well-equipped to monitor, analyze, and optimize memory usage in your Linux systems effectively. Remember that consistent monitoring and proactive management are key to maintaining optimal system performance and preventing memory-related issues before they impact your applications and users.