In this lesson, you will learn how to detect and troubleshoot runaway Bash scripts that consume system RAM by leaking memory.
Understanding the Memory Leak
In shell scripting, a memory leak often occurs when a script creates infinite loops, grows massive arrays, or spawns child processes that refuse to terminate. Unlike languages with garbage collection, if your script keeps appending data to a variable or creating background tasks without cleaning up, the system's available RAM will slowly disappear.
How to Spot the Culprit
When your system slows down, your first step is to identify the process consuming the most memory. Use the top or htop commands to sort processes by memory usage (RES column). If you see a shell script name repeatedly consuming more and more RAM, you’ve found your leak.
To investigate further, we use the ps command to see the memory usage of a specific process ID (PID):
# Display memory usage for a specific process
ps -o pid,user,%mem,cmd -p <PID>
Debugging with Monitoring
If you suspect a script is leaking during execution, you can wrap a monitoring loop around your logic. This creates a "Self-Healing" check (using concepts from our previous lessons) that logs memory growth before the system crashes:
# Log the memory usage of your script (PID: $$) every 5 seconds
while true; do
ps -o rss= -p $$ >> memory_log.txt
sleep 5
done &
If the numbers in memory_log.txt climb indefinitely, your script is leaking. Common causes include:
- Background Jobs: Forgetting to
waitfor background processes, leaving "zombies" that occupy memory slots. - Infinite Appending: Continuously adding strings to a variable within a
whileloop without clearing it. - Unbounded Arrays: Storing logs in an array that never hits a capacity limit or cleanup routine.
By identifying the trend in memory usage early, you can refactor your logic to ensure data is written to disk or cleared from RAM periodically, keeping your system stable.
Key Takeaway: A memory leak in a shell script is typically caused by unbounded growth of variables or uncollected background processes; use ps to track Resident Set Size (RSS) over time to catch these runaway scripts before they exhaust system resources.