Course contentsShow
← Linux
Lesson 172 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Hardware Resource Throttling

Ensure scripts maintain low priority to prevent system instability.

In this lesson, you will learn how to prevent your custom scripts from "hogging" system resources by intentionally lowering their execution priority.

The Concept of "Nice" Values

When you run a script, your computer’s CPU treats it as a standard task. If your script performs heavy calculations or complex regex transformations, it might consume so much processing power that the rest of your system becomes unresponsive. In Linux, we manage this with CPU scheduling priority, often called the "niceness" of a process.

A process can have a "nice" value ranging from -20 (the highest priority) to 19 (the lowest priority). By default, most processes start with a priority of 0. By increasing the nice value, you are essentially telling the kernel, "Please be 'nice' to other programs and only take the CPU cycles that they aren't currently using."

Implementing Throttling

You can launch a script with a lower priority using the nice command. If you have a resource-heavy script, such as one performing recursive directory traversal or complex string manipulation, you can start it like this:

nice -n 15 ./heavy_processing_script.sh

In this example, the -n 15 flag sets the priority significantly lower than the default. If your system starts to lag, the kernel will immediately give CPU time to other tasks before returning to your script.

Adjusting Existing Processes

What if your script is already running and you notice it is slowing down your system? You don’t need to kill it and start over. Instead, use the renice command to change the priority on the fly:

# Find the PID (Process ID) first
renice -n 19 -p 1234

This dynamically shifts the process with PID 1234 to the lowest possible priority. This technique is vital when writing background automation scripts that handle large datasets, ensuring that your system remains snappy for your interactive terminal tasks, like your log streaming or file management operations.

Key Takeaway: Use nice and renice to lower the priority of resource-intensive scripts so they only utilize the CPU overhead without impacting the stability of your core system.