Bash Script to Check Memory Usage Easily
Use the command
free -h inside a Bash script to check memory usage in a human-readable format, for example: #!/bin/bash
free -h.Examples
InputRun script on a system with 8GB RAM
Output total used free shared buff/cache available
Mem: 7.7Gi 2.1Gi 3.5Gi 200Mi 2.1Gi 5.0Gi
Swap: 2.0Gi 0B 2.0Gi
InputRun script on a system with 16GB RAM and some usage
Output total used free shared buff/cache available
Mem: 15.6Gi 6.2Gi 5.0Gi 300Mi 4.4Gi 8.5Gi
Swap: 4.0Gi 512Mi 3.5Gi
InputRun script on a system with very low memory
Output total used free shared buff/cache available
Mem: 1.9Gi 1.7Gi 100Mi 50Mi 100Mi 200Mi
Swap: 1.0Gi 900Mi 100Mi
How to Think About It
To check memory usage in Bash, you can use the
free command which shows total, used, and free memory. Adding the -h option makes the output easy to read by showing sizes in KB, MB, or GB.Algorithm
1
Run the <code>free -h</code> command to get memory usage details.2
Capture the output to display or process further if needed.3
Print the output to the user.Code
bash
#!/bin/bash # Script to check memory usage free -h
Output
total used free shared buff/cache available
Mem: 7.7Gi 2.1Gi 3.5Gi 200Mi 2.1Gi 5.0Gi
Swap: 2.0Gi 0B 2.0Gi
Dry Run
Let's trace running the script on a system with 8GB RAM and some usage.
1
Run free -h command
Command outputs memory stats in human-readable form.
2
Display output
Shows total, used, free memory and swap info.
| total | used | free | shared | buff/cache | available |
|---|---|---|---|---|---|
| 7.7Gi | 2.1Gi | 3.5Gi | 200Mi | 2.1Gi | 5.0Gi |
Why This Works
Step 1: Use of free command
The free command reports memory usage including RAM and swap.
Step 2: Human-readable output
The -h option converts bytes into KB, MB, or GB for easy reading.
Step 3: Simple script
Running free -h inside a script quickly shows memory stats without extra setup.
Alternative Approaches
Using /proc/meminfo
bash
#!/bin/bash
awk '/MemTotal|MemFree|Buffers|Cached/ {print}' /proc/meminfoShows detailed memory info but less user-friendly output.
Using vmstat command
bash
#!/bin/bash
vmstat -s | grep 'memory'Provides memory stats in a different format, useful for performance monitoring.
Complexity: O(1) time, O(1) space
Time Complexity
The script runs a single system command that executes in constant time regardless of memory size.
Space Complexity
No extra memory is used beyond storing the command output temporarily.
Which Approach is Fastest?
Using free -h is fastest and simplest; parsing /proc/meminfo or vmstat adds complexity without speed benefits.
| Approach | Time | Space | Best For |
|---|---|---|---|
| free -h | O(1) | O(1) | Quick, readable memory check |
| /proc/meminfo parsing | O(1) | O(1) | Detailed memory info |
| vmstat | O(1) | O(1) | Performance monitoring |
Use
free -h for a quick and readable memory usage check in Bash.Beginners often forget the
-h option and get hard-to-read byte counts.