In this lesson, you will learn how to boost your script’s performance by saving the output of time-consuming commands into variables so you don't have to run them repeatedly.
The Problem: Redundant Execution
When writing complex scripts, you might find yourself needing the output of a heavy command—like a network diagnostic, a system query, or a search through a massive directory—multiple times within a single execution. Running that same command over and over wastes precious CPU cycles and slows down your script.
Instead of re-executing the logic, we use Command Result Caching.
The Solution: Storing in Variables
Caching is simply the act of capturing a command's output into a variable once, and then referencing that variable whenever you need the data. Think of it as "memorizing" the result so you don't have to "re-solve" the problem.
Imagine you are checking the number of active processes in a loop. Running ps aux | wc -l every time is inefficient. Here is how you cache it:
# Expensive command run once
process_count=$(ps aux | wc -l)
# Later in your script, reuse the 'cached' result
echo "The system currently has $process_count processes."
if [ "$process_count" -gt 100 ]; then
echo "High load detected!"
fi
Why This Matters
By storing the result in $process_count, the script performs the intensive task of listing and counting processes only once. Any subsequent reference to the variable is near-instantaneous because it is pulled directly from your system's memory.
This technique is especially vital when working with loops or complex conditional blocks. By caching your results at the start of your script (or outside of a loop), you prevent the "expensive" operation from multiplying, keeping your execution time consistent regardless of how many times you need that specific piece of information.
Key Takeaway: Cache the output of expensive commands in variables to avoid redundant processing and ensure your script runs at peak efficiency.